Set UITableView's height to the height of its content with Auto Layout
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.
There is another way to do that.
You can add an observer on table view contentSize
variable, and self size when change in table view content.
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var tableHeightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
tableView.layer.removeAllAnimations()
tableHeightConstraint.constant = tableView.contentSize.height
UIView.animate(withDuration: 0.5) {
self.updateViewConstraints()
}
}
The below code worked for me.
- Create an outlet for tableViewHeight.
@IBOutlet weak var tableViewHeight: NSLayoutConstraint!
var tableViewHeight: CGFloat = 0 // Dynamically calcualted height of TableView.
- For the dynamic height of the cell, I used the below code:
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return tableView.estimatedRowHeight
}
- For height of the TableView, with dynamic heights of the TableView Cells:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
print(cell.frame.size.height, self.tableViewHeight)
self.tableViewHeight += cell.frame.size.height
tableViewBillsHeight.constant = self.tableViewHeight
}
Explanation:
After the TableView cell is created, we fetch the frame height of the cell that is about to Display and add the height of the cell to the main TableView.