UITableView 最大尺寸,同时遵守自动布局约束

UITableView max size while respecting autolayout constraints

所以我想要做的是拥有一个在遵守自动布局约束的同时最大化其大小的表格视图。现在我有一个最大尺寸的表格视图,但它不可滚动。

public class ExpandingTableView2: UITableView {

    override public func reloadData() {
        super.reloadData()
        self.setNeedsLayout()
        self.invalidateIntrinsicContentSize()
    }

    override public func layoutSubviews() {
        super.layoutSubviews()
        if !self.bounds.size.equalTo(self.intrinsicContentSize) {
            self.invalidateIntrinsicContentSize()

        }
    }

    override public var intrinsicContentSize: CGSize {
        self.layoutIfNeeded()
        let intrinsicContentSize = super.contentSize
        return intrinsicContentSize
    }
}

您可以通过创建高度限制的出口来根据内容大小计算表格视图高度:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if tableViewHeightConstraint.constant != tableView.contentSize.height && tableViewHeightConstraint.constant < view.frame.height // This will prevent to increase tableview height beyond the view and let it scroll
{
        setupHeightConstraintForTableView(tableView.contentSize.height)
    }

   // rest of the code
}

func setupHeightConstraintForTableView(_ heightValue: CGFloat) {
    tableViewHeightConstraint.constant = heightValue
    self.updateConstraintsIfNeeded()
}

这里重要的是保持控制表视图最大高度的约束高于用于设置其高度的约束。我也把tableview的内容抗压设置为250

public class ExpandingTableView: UITableView {

    @IBOutlet public weak var heightConstraint: NSLayoutConstraint?

    override public func reloadData() {

        guard let heightConstraint = self.heightConstraint, heightConstraint.priority.rawValue < 750  else { return }

        var height: CGFloat = 0.0
        for section in 0..<(self.dataSource?.numberOfSections?(in: self) ?? 1) {
            for row in 0..<(self.dataSource?.tableView(self, numberOfRowsInSection: section) ?? 0) {
                let rowHeight = (self.delegate?.tableView?(self, heightForRowAt: IndexPath(row: row, section: section))) ?? self.rowHeight
                height += rowHeight
            }
        }

        heightConstraint.constant = height

        super.reloadData()
        self.setNeedsLayout()
    }

}