Reputation: 35
I'm trying to use auto layout to dynamically size my UITableViewCell heights. For basic cell design, like to labels in row, I've managed to achieve what I want. But I can't get it working for the following:
Here's the prototype cell:
The image to the left has a fixed height. The title text should grow to fit the complete text. It's a label with rows set to 0. The subtitle should not grow because it will only be short text.
No matter what, I want the bottom space to the superview to be 18 units. That means, if the text's (title + subtitle) height is less than the image's height. The image's bottom constraint should ensure 18 unit bottom margin. If the title grows in height and the total text is higher than the image, the subtitle's bottom constraint should ensure 18 unity bottom margin and the image's bottom constraint should be ignored.
I'm thankful for any suggestions how to solve this, because I'm at a point, where I'm just punching in some random values to the constraints...
Please see the marked answer on how to setup constraints to achieve the layout I needed. If your cells do not layout properly on the tableview's first load, please se this question for a workaround: iOS 8 Auto height cell not correct height at first load
Upvotes: 2
Views: 1857
Reputation: 3997
Firstly, UITableViewAutomaticDimension despite the name isn't documented for auto TableView row heights. Just don't implement heightForRowAtIndexPath
and implement estimatedheightForRowAtIndexPath
as you have.
To address the layout problem, it is not a priority issue but a problem with your constraints. Because you have a fixed top and bottom constraint from your image, the cell will never grow to be larger than the image + 36pt. The solution is to make your top and bottom constraints from your image >= rather than =.
After doing this, you will probably find that there are red warnings in IB for ambiguous constraints. This is because with greater than or equal to constraints, the layout can't determine the correct Y position of the image view. The solution: add a center Y in superview constraint to the imageView.
Upvotes: 2