UITableView的最大大小,同时注意自动布局约束

时间:2018-09-17 11:20:57

标签: ios uitableview autolayout intrinsic-content-size

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

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
    }
}

2 个答案:

答案 0 :(得分:1)

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

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()
}

答案 1 :(得分:0)

在这里重要的是使控制表格视图的最大高度的约束高于用于设置其高度的约束。我还将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()
    }

}