8

I make custom cell with 2 multiline labels and pin this labels to all sides. When in -tableView:heightForRowAtIndexPath: for iOS >= 8 I return UITableViewAutomaticDimension. But when table view appears the cell height is bigger than should be. After I scroll down and then scroll up the cell takes the normal height. How to fix this behavior?

Code for height:

   - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
        return UITableViewAutomaticDimension;
    }

    static CCTopicTableViewCell *cell;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        cell = [tableView dequeueReusableCellWithIdentifier:@"topicCellIdentifier"];
    });
    cell.topic = [self.topics topicAtIndexPath:indexPath];

    cell.bounds = CGRectMake(0, 0, CGRectGetWidth(self.tableView.bounds), CGRectGetHeight(cell.bounds));

    [cell setNeedsLayout];
    [cell layoutIfNeeded];

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

And the result:

After scrolling:

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
rabbitinspace
  • 884
  • 8
  • 21

4 Answers4

10

The problem is gone when I don't set tableView's estimatedRowHeight for iOS 8 and update preferredMaxLayoutWidth every time when sets the text for multiline labels

rabbitinspace
  • 884
  • 8
  • 21
  • Thanks, this fixed my issue. Not sure I understand why it fixes it but I'm sure after more researching of the topic It'll come to me. Thanks again! – Josh Valdivieso Mar 27 '15 at 18:40
  • I kept estimatedRowHeight as it is, added preferredMaxLayoutWidth on problematic UILabel before setting attributedString and it worked. +1 for you! – iAkshay Jul 05 '19 at 09:50
4

I solved this issue by setting "text" property of multiline labels to "nil":

override func prepareForReuse() {
    _label.text = nil
}

Also table properies "estimatedRowHeight" and "rowHeight" should be set correctly:

_tableView.estimatedRowHeight = 44
_tableView.rowHeight = UITableViewAutomaticDimension
Murlakatam
  • 2,729
  • 2
  • 26
  • 20
2

Automatic dimension is not working well for some UILabel if that label is aligned with different label by top edges or bottom edges. Just make sure that you do not have such alignments.

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
2

Set automatic dimension in viewDidLoad() method or viewWillAppear() (both code in same place)

    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.estimatedRowHeight = 160.0;//(Maximum Height that should be assigned to your cell)

Visit Using Auto Layout in UITableView for dynamic cell layouts & variable row heights an intuitive guide for both iOS 7 and iOS 8

Community
  • 1
  • 1
Mihir Gurjar
  • 375
  • 1
  • 7