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

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

问题描述

我有一个视图,里面有两个标签和一个表视图.我希望标签 1 始终保持在我的表视图上方,而标签 2 始终位于表视图下方.问题是 Table View 需要自动调整大小,这意味着要么增加高度,要么减少.

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.

现在我有一个约束,说 Table View 的高度总是等于 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() {
    tableHeightConstraint.constant = tableView.contentSize.height
    super.updateViewConstraints()
}

然后你必须确保 Label2 有一个顶部约束,它是 greaterThanOrEqual 到表格视图的底部.并且您还必须将 table view 的高度约束的优先级从 Required 更改为 High 以避免在 table view 的 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天全站免登陆