February 13, 2017 · Ralf Ebert » iOS Developer Blog »

Using Auto Layout Constraints for the height of UITableView cells

This snippet describes how to use auto layout constraints to resize cell views according to their content:

Dynamic Cell Heights

The height of a table cell is configured by setting the row height for the cell object in Interface Builder:

UITableViewCell: Row Height

or it can be computed programmatically using the method tableView:heightForRowAtIndexPath::

class ExampleTableViewController: UITableViewController {

    // ...
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 55
}

}

It gets more difficult if the cell height depends on the contents of the views and can not be calculated without the views itself - for example a label with multi-line text. One convenient way is to use layout constraints here to automatically adjust the cell size.

To do this, you need to configure the table with the .rowHeight = UITableViewAutomaticDimension property to automatically determine the row height, and set the estimatedRowHeight property to an estimate of the row height. This doesn’t need to be exact - the height for visible cells is determined by the actual size. However, if there are major deviations between the estimated value and the actual altitude, the scroll indicator of the table will jump. To prevent this, you can optionally override tableView:estimatedHeightForRowAtIndexPath: to calculate more accurate estimates:

class ExampleTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 44
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    // optionally, return an calculated estimate for the cell heights
}
    
    // ...

For the cell, create layout constraints that force the auto-layout mechanism to change the cell height. In this example, besides the upper margin and the spacing between the labels there is also a constraint for the bottom margin. These constraints can only be solved by setting the height of the cell view:

Cell Constraints

When editing these constraints in the Interface Builder, you need to be aware that Interface Builder never changes the cell height - therefore, such a configuration will trigger a content ambiguity conflict:

Content Ambiguity Konflikt

You can solve this conflict by manually setting the cell height to the correct height for the content in the prototype cell.

Example project

CellLayoutConstraints.zip

More information

Btn read 3c0e607615 iOS Developer Blog
Btn subscribe 930758687e Subscribe: Email · Twitter
Btn training bbbdf557d2 Next iOS training: 25. Februar - 01. März 2019, Stuttgart
Btn about 5378472193 About me · Contact