带有高度变化的子视图的自定义TableViewCell

Custom TableViewCell with Subview whose height changes

我正在使用 TableView 并有一个自定义 TableViewCell,我已将子视图添加到其中。

问题是我有时需要更改子视图的高度,因此,table 的 contentView 以及行的高度都必须更新。

自定义TableViewCell的子view用黄色背景表示

这些图像显示了我的模拟器中当前发生的情况。

  1. 加载中

  2. 导致子视图高度增加的事件后

处理此类问题的最佳方法是什么?

我应该使用约束吗?如果是这样,我应该使用什么样的约束?每次子视图的大小更改时,我是否也必须重新加载 table 视图?

这是我目前用于自定义 TableViewCell 的代码:

import UIKit

class CustomCell: UITableViewCell {

    var newView: UIView!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        self.newView = UIView(frame: self.frame)
        self.newView.backgroundColor = .yellowColor()
        self.addSubview(newView)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.newView.frame.size.width = self.frame.size.width // because self.frame.width is different than it was in the init method
   }

    func somethingHappenedThatMySubviewHasToIncreaseInHeight() {
        self.newView.frame.size.height = self.frame.size.height + 40
    }
}

最好的方法是使用自动布局和自动调整单元格大小。在故事板中为您的自定义单元设置约束。

您将不需要重新加载 tableView。每个单元格都会根据其子视图的垂直度 space 自动调整高度。

有关详细信息,请参阅 smileyborg in his answerUsing Auto Layout in UITableView for dynamic cell layouts & variable row heights 的详细演练。