D
D
deleted-mezhevikin2014-04-14 22:46:13
Objective-C
deleted-mezhevikin, 2014-04-14 22:46:13

Calculating height of UITableViewCell from text height?

There are cells with dynamic height, I count using the method:

- (CGFloat)heightByTextLabel
{
    float width = self.contentView.frame.size.width;
    float margin = 10;
    CGSize constraint = CGSizeMake(width - (margin * 2), 2000);
    CGSize size = [self.textLabel.text
                   sizeWithFont: self.textLabel.font
                   constrainedToSize:constraint
                   lineBreakMode:self.textLabel.lineBreakMode];
    CGFloat height = MAX(size.height, 44.0f);
    return  height + (margin * 2);
}

in 90% it is calculated correctly, but sometimes incorrectly (lower height)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kaspartus, 2014-04-15
@kaspartus

It looks quite sensible, in theory it should work, I would suggest 2 options here:
1. Debug. We put breakpoints, we log and so on.
2. In the book I saw an example for dynamically calculating the height of a cell.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  static UILabel* label; 
  if (!label) {
    label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, FLT_MAX, FLT_MAX)];
    label.text = @"test";
  }
  label.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
  [label sizeToFit];
  return ceilf(label.frame.size.height * 1.7); 
}

I tried it myself - it works. I think changing the height increase from x1.7 to +2margin will not be a problem.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question