首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

我的TableViewCell不会根据它内部动态变化的视图来改变高度

TableViewCell是iOS开发中用于展示列表数据的一种视图控件。通常情况下,TableViewCell的高度是固定的,但是当内部的视图动态变化时,需要根据内部视图的内容来动态调整TableViewCell的高度。

为了实现TableViewCell的高度根据内部视图动态变化,可以采用以下步骤:

  1. 在TableViewCell的布局中,将内部视图的约束设置为自适应的约束。这意味着内部视图的高度会根据其内容自动调整。
  2. 在TableViewCell的代码中,重写layoutSubviews方法。在该方法中,调用super.layoutSubviews()来确保父类的布局方法得到执行。然后,更新内部视图的约束,并计算内部视图的高度。
  3. 在TableView的代理方法heightForRowAt中,返回计算得到的TableViewCell的高度。可以使用systemLayoutSizeFitting方法来计算TableViewCell的高度,该方法会根据内部视图的约束自动计算高度。

以下是一个示例代码:

代码语言:txt
复制
class CustomTableViewCell: UITableViewCell {
    // 内部视图
    var dynamicView: UIView!
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        // 创建内部视图
        dynamicView = UIView()
        dynamicView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(dynamicView)
        
        // 添加内部视图的约束
        dynamicView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10).isActive = true
        dynamicView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
        dynamicView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
        dynamicView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10).isActive = true
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 更新内部视图的约束
        // ...
        
        // 计算内部视图的高度
        let dynamicViewHeight = dynamicView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
        
        // 更新TableViewCell的高度
        frame.size.height = dynamicViewHeight + 20
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// 在TableView的代理方法中返回计算得到的TableViewCell的高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell") as! CustomTableViewCell
    // 配置TableViewCell的数据
    // ...
    cell.layoutIfNeeded()
    return cell.frame.height
}

这样,当内部视图的内容发生变化时,TableViewCell的高度会自动根据内部视图的大小进行调整。

腾讯云相关产品和产品介绍链接地址:

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券