使用“自动布局”将UITableView的高度设置为其内容的高度 [英] Set UITableView's height to the height of its content with Auto Layout

查看:1601
本文介绍了使用“自动布局”将UITableView的高度设置为其内容的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个View,里面有两个标签和一个Table View。我希望标签1始终位于我的表格视图上方并标记为2,位于表格视图下方。问题是表视图需要自动调整大小意味着增加高度还是减少。

I have a View which has two labels and a Table View inside it. I want label 1 to always stay above my Table View and label 2, to be below the Table View. The problem is that the Table View needs to auto-size meaning either increase in height or decrease.

现在我有一个约束,表示表视图的高度始终等于85和一个 @IBOutlet 到高度约束,我可以改变常量。

Right now I have a constraint saying the Table View's height is always equal to 85 and a @IBOutlet to the height constraint where i'm able to change the constant.

我是猜测我需要将常数更改为所有单元格的高度,但我不确定如何。

I'm guessing I need to change the constant to the height of all the cells, but i'm not sure how.

推荐答案

您必须在UIViewController中覆盖 updateViewConstraints()并将高度约束的常量设置为tableView.contentSize .height:

You have to override updateViewConstraints() in your UIViewController and set the height constraint's constant to tableView.contentSize.height:

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

然后你有确保 Label2 有一个顶级约束 greaterThanOrEqual 到表视图的底部。而且你还必须将表格视图的高度约束的优先级从必需更改为,以避免在表格视图中出现冲突的约束 contentHeight 大于可用高度。

Then you have to make sure that Label2 has a top constraint that is greaterThanOrEqual to the table view's bottom. And you also have to change the table view's height constraint's priority from Required to High to avoid conflicting constraints when the table view's contentHeight is larger than the available height.

这篇关于使用“自动布局”将UITableView的高度设置为其内容的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆