简体   繁体   English

自动调整UITableView的高度

[英]Auto Fit Height of UITableView

I have multiple tableviews in my ViewController and each tableview has different number of rows, please see image below: 我的ViewController中有多个表视图,每个表视图具有不同的行数,请参见下图: 在此处输入图片说明

Is there any way to match the height of the tableview according to its number of rows? 有什么方法可以根据表格视图的行数来匹配其高度吗?

In your view controller, put code similar to the following: 在视图控制器中,放入类似于以下内容的代码:

override func updateViewConstraints() {
    super.updateViewConstraints()
    tableViewHeightConstraint.constant = tableView.contentSize.height;
}

Where tableViewHeightConstraint is an @IBOutlet to NSLayoutConstraint . 其中tableViewHeightConstraint@IBOutletNSLayoutConstraint Obviously with multiple table views you will need to reference multiple height constraints, so you'd just have one line in updateViewConstraints for each table view you want. 显然,对于多个表视图,您将需要引用多个高度约束,因此对于所需的每个表视图,在updateViewConstraints只有一行。

The advantage of this technique is that it takes all of the table view's content into account. 这种技术的优点是它考虑了所有表视图的内容。 It handles grouping, automatic cell height, etc. 它处理分组,自动像元高度等。

You have to determine how many cells you have, then override 您必须确定有多少个单元格,然后覆盖

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
  return CGRectGetHeight(self.tableView.bounds) / self.tableView.numberOfRowsInSection(indexPath.section)  
}

Btw, I suppose making use of header cells would be a better idea than implementing multiple tableviews. 顺便说一句,我想使用标头单元比实现多个表视图更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM