Question

I am trying to create multi-line dynamic UILabels in UITableViewCells. I have a custom UITableViewCell that has a 'comment' label. The cell and the label are created in storyboard.

I can compute the heights of the UITableViewCells properly based on the multi-line data to be stored in the UILabel (using heightForRowAtIndexPath). However, my problem lies in the actual UILabel content. The UILabel content will display only 1 line of data on table load. However, once a cell containing multiline UILabel data moves offscreen and comes back on screen, the multi-line data appears properly in the UILabel with multiple lines. Is there any way to fix this so that the multi-line data appears properly on table load?

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell *cCell = (CustomCell *)cell;
    MyObject = [myArray objectAtIndex:indexPath.row];

    cCell.commentLabel.frame = CGRectMake(65.0f, 28.0f, 243.0f, 200.0f);
    cCell.commentLabel.text = MyObject.multi_line_text_data;
    cCell.commentLabel.adjustsFontSizeToFitWidth = NO;
    cCell.commentLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    cCell.commentLabel.font = [UIFont systemFontOfSize:13.0];
    cCell.commentLabel.lineBreakMode = NSLineBreakByWordWrapping;
    cCell.commentLabel.numberOfLines = 0;
    [cCell.commentLabel sizeToFit];

}

Thanks!

Was it helpful?

Solution

Since you're doing this in the storyboard, you can set the necessary label properties there (lineBreakMode and number of lines). Just give the label a specific width constraint and constraints to the top, bottom, and left sides of the cell. Then, in code use sizeWithFont:constrainedToSize:lineBreakMode: in heightForRowAtIndexPath: to calculate the appropriate height for the cell based on the content of the label -- the label, because of its constraints, will expand along with the cell to the proper size. Something like this:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGSize rowSize = [self.theData[indexPath.row] sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(260, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
    return rowSize.height + 30;
}

Here, 260 was the width I gave my label in IB, and the 30 is a fudge factor (determined empirically) to account for padding above and below the label.

OTHER TIPS

I met the same problems. Unchecking Autolayout can fix it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top