increase TableView height based on cells
The below code worked for me with UITableViewCell who has AutomaticDimension.
- 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.
Without setting and resetting a height constraint you can resize a table view based on its content like so:
class DynamicHeightTableView: UITableView {
override open var intrinsicContentSize: CGSize {
return contentSize
}
}
Add these lines after your cells are created. Because it returns 0 height in viewDidLoad()
var frame = tableView.frame
frame.size.height = tableView.contentSize.height
tableView.frame = frame
UPDATE
//After Tableviews data source values are assigned
tableView.reloadData()
tableView.layoutIfNeeded()
tableView.heightAnchor.constraint(equalToConstant: tableView.contentSize.height).isActive = true