How to Calculate Table Cell Height Using Auto-Layout

No time to write it clearly, I just post some code which helps me finish it.

  1. Use Xib, not storyboard.
  2. Add the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

static TBGrowRecordCell *sizingCell = nil;

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
});
TBGrowRecordEntity *record = self.recordArray[indexPath.row];
sizingCell.contentLabel.text = record.content;
[sizingCell layoutIfNeeded];

//Notice that: this is "sizingCell.contentView", not "sizingCell"
CGFloat height = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
return height;
}

Notice that: this is “sizingCell.contentView”, not “sizingCell”.

  1. Choosing the checkbox constraint to margins.

  1. Set lines to 0.
  2. choosing the checkbox explicit.

Done! The effect is that the UIlabel named sizingCell.contentLabel will resize by text’s length, and the UITableViewCell will resize by the UILabel.

Refer to:

Dynamic Table View Cell Height and Auto Layout

Using auto-layout to calculate table cell height

http://stackoverflow.com/questions/25265173/how-can-a-get-the-auto-layout-size-of-the-uicollectionviewcells-in-ios-8-syste