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:
Setup
- I'm using Swift and Xcode 6.4 targeting iOS8 and above.
- TableView row height is set to UITableViewAutomaticDimension.
- Estimated height for TableView is set to 100, which should generally be close to the final height.
- The title's vertical hugging priority is set to low (250).
- Didn't change the other elements hugging and compression priority.
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.
My constraints setup
- For the image leading and top constraint set to 18. Trailing constraint to title and subtitle label set to 18. Bottom constraint set to 18 with priority low (249).
- For the title label top and trailing constraint to superview set to 18. Leading constraint to image 18. Bottom constraint to subtitle is 0.
- For the subtitle label top constraint to title label is 0. Trailing space to superview is 18. Leading constraint to image is 18. Bottom constraint to superview is 18 with priority low (250).
The Problem
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...
Update
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