Gianluca Carpi Gianluca Carpi - 1 year ago 63
iOS Question

Set the height of the cell according to the height of the text content

I have a table containing dynamic cell. In each cell, I have textLabel and detailTextLabel. I would like to set the cell height equal to the sum of the height of the textLabel and detailTextLabel.This is my code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

cell.textLabel.numberOfLines = 0;

cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;

cell.detailTextLabel.numberOfLines = 0;

cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;



return cell;

How can I do this?

Answer Source

If you're using AutoLayout on iOS8, a important part is to tell the UITableView to be "autolayouted":

self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 50.0; // your estimated average cell height

Also, it would be best to use a custom cell and override the Method "layoutSubviews":

- (void)layoutSubviews
    [super layoutSubviews];

    // Make sure the contentView does a layout pass here so that its subviews have their frames set, which we
    // need to use to set the preferredMaxLayoutWidth below.
    [self.contentView setNeedsLayout];
    [self.contentView layoutIfNeeded];

    self.details.preferredMaxLayoutWidth = CGRectGetWidth(self.details.frame);

Checkout this Example Project at github.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download