How to set automatic height of static cell in UITableViewController?

bpiec picture bpiec · Mar 31, 2015 · Viewed 26.7k times · Source

I am using IB and storyboard and I defined UITableViewController. There I defined three static cells. The first two should have a given height but the last one should automatically fill the remaining space (anchor to the bottom of the view). How can I achieve this? I can use autolayout for the controls inside the cell but it is greyed out for the cell itself.

The best solution would be to do this from IB but programmatic solutions are also welcomed.

EDIT:

This is how it looks in my storyboard (colors are for visualizing separate controls, each control has required constraints): Storyboard view controller

And after launching: Simulator view Note that the text view ends below the bottom of the screen.

I forgot to mention that I target iOS 7.0+.

Answer

Ryan Romanchuk picture Ryan Romanchuk · Oct 19, 2015

You can actually use UITableViewAutomaticDimension with static cells. Design your static cells per usual and manually set your cells as dynamic heights by adding

tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 240 // Something reasonable to help ios render your cells

Now override the heightForRow delegate

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

The only other caveat I noticed with this technique is that you must use NSAutolayout to create a constraint to the bottom container (the UITableViewCell's container). So let's say you have a container inside the cell's contentView that will have a dynamic height, for this to render properly you need to create a bottom space constraint.

If you have some static cells that do have fixed heights I recommend returning that size by switching on row in tableView:heightForRowAtIndexPath:indexPath