How to set automatic height of static cell in UITableViewController?

I covered this in a blog post using a static table view and setting the cell heights using auto layout. The cells are all defined in interface builder.

You have to enable the automatic cell heights in code but that's only a couple lines.

I show everything including IB and code.

Take a look

http://www.oliverfoggin.com/using-a-static-uitableview-as-a-layout-device/


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


Be sure to override heightForRowAtIndexPath! Otherwise it will not display correctly from my experiences

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 
{
    return UITableViewAutomaticDimension
} 

Ok try this

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{

    if indexPath.row == 0 { 
        return firstRowHeight
    }
    else if indexPath.row == 1 { 
        return secondRowHeight 
    }
    else { 
        return tableView.frame.size.height - firstRowHeight - secondRowHeight 
    }
}

The only thing that may be a problem is that this method is going to run before the view sets the tableView height