How to get height of UITableView when cells are dynamically sized?

ios, swift, uitableview

Solution

I finally hacked out a solution:

`tableView.contentSize.height` will not work for dynamic cells because they will only return the number of cells * `estimatedRowHeight`.

Hence, to get the dynamic table view height, you look for all visible cells, and sum up their heights. Note that this only works for table views that are shorter than your screen.

However, before we do the above to look for visible cells, it is important to know that note we need to get the table view on the screen so that we can obtain visible cells. To do so, we can set a height constraint for the table view to some arbitrarily large number just so it appears on the screen:

Set height of table view constraint:

// Class variable heightOfTableViewConstraint set to 1000
heightOfTableViewConstraint = NSLayoutConstraint(item: self.tableView, attribute: .height, relatedBy: .equal, toItem: containerView, attribute: .height, multiplier: 0.0, constant: 1000)
containerView.addConstraint(heightOfTableViewConstraint)

Call tableView.layoutIfNeeded(), and when completed, look for the visible cells, sum up their height, and edit the `heightOfTableViewConstraint`:

UIView.animate(withDuration: 0, animations: {
    self.tableView.layoutIfNeeded()
    }) { (complete) in
        var heightOfTableView: CGFloat = 0.0
        // Get visible cells and sum up their heights
        let cells = self.tableView.visibleCells
        for cell in cells {
            heightOfTableView += cell.frame.height
        }
        // Edit heightOfTableViewConstraint's constant to update height of table view
        self.heightOfTableViewConstraint.constant = heightOfTableView
}

Problem

I have a UITableView with cells that are dynamically sized. That means I have set: ``` tableView.estimatedRowHeight = 50.0 tableView.rowHeight = UITableViewAutomaticDimension ``` Now I want to get the height of the whole table view. I tried getting it through `tableView.contentSize.height` but that only returns the estimated row height, and not the actual dynamic height of the table view. How do I get the dynamic height of the whole table view?

Original source