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

UITableViewCell中的简单UIStackView无法正确计算IB中的高度

是因为在Interface Builder(IB)中,UIStackView的高度是根据其内部的子视图来计算的。而在UITableViewCell中,由于在Interface Builder中无法预先知道动态加载的数据,所以无法正确计算UIStackView的高度。

解决这个问题的方法是使用自动布局和动态计算高度的技术。以下是一种可能的解决方案:

  1. 在UITableViewCell的子类中,使用自动布局来设置UIStackView和其内部的子视图的约束。确保UIStackView的上下左右边距与UITableViewCell的上下左右边距相等,并设置合适的约束来保证UIStackView内部子视图的布局。
  2. 在UITableViewCell的子类中,重写layoutSubviews方法。在这个方法中,调用super.layoutSubviews()来确保父类的布局被正确执行。然后,根据UIStackView内部子视图的约束和内容来计算UIStackView的高度。
  3. 在UITableViewDelegate的tableView(_:heightForRowAt:)方法中,返回计算得到的UIStackView的高度。可以使用自动布局的systemLayoutSizeFitting(_:withHorizontalFittingPriority:verticalFittingPriority:)方法来计算UIStackView的高度。

以下是一个示例代码:

代码语言:swift
复制
class CustomTableViewCell: UITableViewCell {
    @IBOutlet weak var stackView: UIStackView!
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 计算UIStackView的高度
        let stackViewHeight = stackView.systemLayoutSizeFitting(
            CGSize(width: bounds.width, height: CGFloat.greatestFiniteMagnitude),
            withHorizontalFittingPriority: .required,
            verticalFittingPriority: .fittingSizeLevel
        ).height
        
        // 更新UIStackView的高度约束
        stackView.heightAnchor.constraint(equalToConstant: stackViewHeight).isActive = true
    }
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    // ...
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
        
        // 配置UIStackView的子视图
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell") as! CustomTableViewCell
        
        // 配置UIStackView的子视图
        
        cell.setNeedsLayout()
        cell.layoutIfNeeded()
        
        // 计算UIStackView的高度
        let stackViewHeight = cell.stackView.systemLayoutSizeFitting(
            CGSize(width: tableView.bounds.width, height: CGFloat.greatestFiniteMagnitude),
            withHorizontalFittingPriority: .required,
            verticalFittingPriority: .fittingSizeLevel
        ).height
        
        return stackViewHeight
    }
    
    // ...
}

这样,UITableViewCell中的简单UIStackView就可以正确计算IB中的高度了。

注意:以上示例代码仅为参考,具体实现可能需要根据实际情况进行调整。

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

相关·内容

领券