Set UITableView's height to the height of its content with Auto Layout

前端 未结 7 1427
野的像风
野的像风 2020-12-04 13:40

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

7条回答
  •  感情败类
    2020-12-04 13:59

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

    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.

提交回复
热议问题