Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set automatic height of static cell in UITableViewController?

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+.

like image 368
bpiec Avatar asked Mar 31 '15 12:03

bpiec


People also ask

How do you make a table dynamic cell height?

To get dynamic cell heights working properly, you need to create a custom table view cell and set it up with the right Auto Layout constraints. In the project navigator, select the Views group and press Command-N to create a new file in this group.


1 Answers

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

like image 173
Ryan Romanchuk Avatar answered Sep 20 '22 04:09

Ryan Romanchuk