Project example: http://cl.ly/2j0A1J203f3h
I am trying to use Auto Layout to dynamically determine the height of each cell, so some cells may contain more content than others. For this, I am using https://stackoverflow.com/a/3/2/7 and the accompanying GitHub example .
I have a subclass UITableViewCell
called CSPostCell
that I created on a Storyboard, and placed a UILabel
in with a maximum of 5 lines of text in the label.
Just for the purpose, I have only two cells in the table and as two different pieces of text for labels (one longer), which is configured in cellForRowAtIndexPath:
:
- (CSPostCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CSPostCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SelfPostCell" forIndexPath:indexPath];
cell.postTitle.text = indexPath.row == 0 ? @"Short title" : @"Long long long title. Holy crap this is one long title. When does it end? Oh right now.";
[cell setNeedsUpdateConstraints];
return cell;
}
Then I return the height of each cell as such:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CSPostCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SelfPostCell"];
cell.postTitle.text = indexPath.row == 0 ? @"Short title" : @"Long long long title. Holy crap this is one long title. When does it end? Oh right now.";
cell.postTitle.preferredMaxLayoutWidth = tableView.bounds.size.width - 40;
[cell setNeedsUpdateConstraints];
[cell updateConstraintsIfNeeded];
[cell.contentView setNeedsLayout];
[cell.contentView layoutIfNeeded];
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
return height;
}
This is a more or less exact copy from the GitHub example repo .
However, when I run the application in the simulator, it does not work as it should. The height is dynamic and can be adjusted for longer pieces of text, but not enough so that the text is not cropped. See image below:

In this case, the second cell label should show a different line to complete the text, but it is turned off.
Why doesn't it display all the text?