1


I've got some strange problem related to dynamically sized cells, auto layout and size classes. My test project is completely based on Ray's tutorial. It seems that the only difference is UILabels's font sizes for size classes. The height calculation is wrong when I set another font size for label in some size class. I've made screenshot to illustrate it.

Wwith wrong cell's height calculations:

enter image description here

With correct cell's height calculations:

enter image description here

In addition, I've pushed test project to the github.

EDITED:

ViewController.m

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  return [self heightForCellAtIndexPath:indexPath];
}
- (CGFloat)heightForCellAtIndexPath:(NSIndexPath *)indexPath {
  static CustomTableViewCell *sizingCell = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sizingCell = [self.tableView dequeueReusableCellWithIdentifier:kBasicCell];
  });
  [self configurateCell:sizingCell atIndexPath:indexPath];
  return [self calculateHeightForCell:sizingCell];
}

- (CGFloat)calculateHeightForCell:(CustomTableViewCell *)cell {
  cell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.tableView.frame), CGRectGetHeight(cell.bounds));

  [cell setNeedsLayout];
  [cell layoutIfNeeded];

  CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
  return size.height +1.0f;
} 

CustomLabel.m

- (void)setBounds:(CGRect)bounds {
  [super setBounds:bounds];

  if (self.numberOfLines == 0 && bounds.size.width != self.preferredMaxLayoutWidth) {
    self.preferredMaxLayoutWidth = self.bounds.size.width;
    [self setNeedsUpdateConstraints];
  }
Gladkov_Art
  • 23
  • 1
  • 5

1 Answers1

0

Since you're already using Auto Layout, I'd recommend also taking advantage of self-sizing cells. You won't need any row height calculation, as iOS can adjust the cell's height automatically, based on the UILabel height.

  1. Add Auto Layout constraints to your contentView's UILabel. This will cause the cell to adjust its contentView height based on the label's contents.
  2. Enable row height estimation.

    self.tableView.rowHeight = UITableViewAutomaticDimension; self.tableView.estimatedRowHeight = 44.0;

For more information, see the detailed walkthrough by smileyborg in his answer to Using Auto Layout in UITableView for dynamic cell layouts & variable row heights.

Community
  • 1
  • 1