Self-sizing UITableViewCell’s

Before iOS 7, we had to use either the rowHeight property on UITableView, or the tableView(_:, heightForRowAtIndexPath:) delegate method to specify the height of a table view cell; to make matters worse, we often needed complex calculations to determine the height of each cell at runtime.

iOS 7 introduced the concept of estimated row heights via the estimatedRowHeight property on UITableView, and the tableView(_:, estimatedHeightForRowAtIndexPath:) delegate method. This allowed for just-in- time row height delegate method calls just as the cell was about to come into view. Although this was a major improvement, it still placed the responsibility of calculating row height on the delegate instead of the cell. Since a cell is responsible for its own layout, surely it should also determine its own height?

And this is precisely what happens in iOS 8. By ensuring the Auto Layout constraints used in the cells layout properly determine the cells height, we can let UIKit handle the rest. There are only two changes we need to make in order to achieve self- sizing cells:

  • The table views rowHeight property needs to be set to UITableViewAutomaticDimension
  • The estimatedCellHeight needs to be set to a non-zero value

Here’s what you need to remember about self-sizing table view cells:

  • The table view determines the width
  • Your Auto Layout constraints must define the height, without any ambiguity
  • The rowHeight property on the table view must be set to UITableViewAutomaticDimension
  • estimatedRowHeight must be set to non-zero, but you should try and set this a close approximation, as too big a difference between the estimate and the actual will cause the table view to jump when scrolling. This value is used solely to calculate the length of the scroll bar in the tableview – a process that would otherwise require calculating the height of each cell individually.

tomkausch

Leave a Reply

Your email address will not be published. Required fields are marked *