Is it possible to obtain a dynamic table view section header height using Auto Layout?

Jordan H picture Jordan H · Apr 5, 2015 · Viewed 72.6k times · Source

New in iOS 8, you can obtain 100% dynamic table view cells by simply setting the estimated row height, then layout your elements in the cell using Auto Layout. If the content increases in height, the cell will also increase in height. This is extremely useful, and am wondering if the same feat can be accomplished for section headers in a table view?

Can one, for example, create a UIView in tableView:viewForHeaderInSection:, add a UILabel subview, specify auto layout constraints for the label against the view, and have the view increase in height to fit the label's contents, without having to implement tableView:heightForHeaderInSection:?

The documentation for viewForHeaderInSection states: "This method only works correctly when tableView:heightForHeaderInSection: is also implemented." I haven't heard if anything has changed for iOS 8.

If one cannot do that, what is the best way to mimic this behavior?

Answer

Jordan H picture Jordan H · Apr 21, 2015

This is possible. It is new right alongside the dynamic cell heights implemented in iOS 8.

It's very simple. Just add this in viewDidLoad:

self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
self.tableView.estimatedSectionHeaderHeight = 25;

Then override viewForHeaderInSection and use Auto Layout to constrain elements in your view as seen fit. That's it! No need to implement heightForHeaderInSection. And actually the sectionHeaderHeight doesn't need not be stated either, I just added it for clarity.

Note that in iOS 11, cells and header/footer views use estimated heights by default. The only thing to do is provide an estimated height to better inform the system what to expect. The default value is UITableViewAutomaticDimension but you should provide a better estimate that is the average height they will be if possible.