Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Auto-Layout: Dynamic height for table view cell

I have a table view with a bunch of cells (custom cell, which only has its content view).

In tableView:cellForRowAtIndexPath: I'm adding a predefined UIView (which has several subviews) to the content view of the custom cell. I set up all constraints for the UIView and its subviews before.

Last but not least, I set the vertical and horizontal constraints for the content view of my custom cell (superview) and the UIView, which was added before (subview).

The constraint strings look like this:

    H:|[view]|
    V:|[view]|

Unfortunately, I still get the default height for all table view cells. I'm wondering If there's a way to let auto layout do the calculation of the height automatically according to content size.

like image 648
Chrizzor Avatar asked May 21 '13 16:05

Chrizzor


2 Answers

Check out my detailed answer to this question here: https://stackoverflow.com/a/18746930/796419

It takes a bit of work to set up, but you can absolutely have Auto Layout constraints driving a completely dynamic table view without a single hardcoded height (and let the constraint solver do the heavy lifting and provide you with the row height).

like image 139
smileyborg Avatar answered Oct 30 '22 02:10

smileyborg


Auto Layout won't help with the cell height. You'll need to set that in tableView:heightForRowAtIndexPath. I guess you're probably asking this because your cell heights are variable, not fixed. i.e., they depend on the content.

To resolve that, pre-calculate the cell heights and store them in an array. Return the value for the appropriate indexPath in the tableView:heightForRowAtIndexPath method.

Be sure to calculate content sizes on the main thread, using sizeThatFits of UILabel classes and such like.

If your calculation is intensive, do the majority of it off main apart from the view related methods such as sizeThatFits.

like image 40
Max MacLeod Avatar answered Oct 30 '22 03:10

Max MacLeod