UILabel in UITableViewCell with auto layout has wrong height

autolayout, ios, uitableview

Solution

Adding this in the cell subclass works:

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self.contentView layoutIfNeeded];
    self.myLabel.preferredMaxLayoutWidth = self.myLabel.frame.size.width;
}

I found this on http://useyourloaf.com/blog/2014/02/14/table-view-cells-with-varying-row-heights.html.

Update 1: This answer was for iOS 7. I find auto layout in table view cells to be very unreliable since iOS 8, even for very simple layouts. After lots of experimentation, I (mostly) went back to doing manual layout and manual calculation of the cell's height.

Update 2: I've run some tests on iOS 9 and it seems that `UITableViewAutomaticDimension` finally works as advertised. Yay!

Problem

I have a `UITableView` with cells that have a fixed height of 100 points. The cells are created in a xib file that uses 3 constraints to pin a `UILabel` to the left, right and top edges of the cell's `contentView`. The label's vertical hugging priority is set to 1000 because I want the cell's height to be as small as possible. When the width of the cell in the xib file is set to 320 points, the same as the tableView's width on the iPhone, autolayout works as expected. However, when I set the width of the cell to less than 320 points, I get unexpected results. (I want to use the same cell in tableViews that have different widths, e.g. in a universal app) For example: when I set the width to 224 points and give the label a text that takes up 2 lines at that width, the label's height will increase to fit the 2 lines, but when the cell is then resized to 320 points to fit in a tableView of that width, the text only takes up 1 line, but the height of the label remains at 2 lines. I have put a sample project on GitHub to demonstrate the problem: https://github.com/bluecrowbar/CellLayout Is there a way to make the `UILabel` always resize to hug its text content?

Original source

Related problems