Set UITableViewCell's height depending on the

2019-04-15 12:16发布

问题:

I would really appreciate it if you could tell me how I could set the height of a UITableViewCell depending on the height of a UILabel.

My current code to set the UILabel's height is:

cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
           cell.textLabel.numberOfLines = 0;
            cell.textLabel.text = [self getItemForKey:kSummary];
            cell.textLabel.font = [UIFont systemFontOfSize:15];
            cell.textLabel.textColor = [UIColor colorWithRed:54.0f/255.0f green:54.0f/255.0f blue:54.0f/255.0f alpha:1.0f];
            CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
            CGSize labelSize = [[cell.textLabel text] sizeWithFont:[cell.textLabel font] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
            cell.textLabel.frame = CGRectMake( 0, 0, 280, labelSize.height);

回答1:

You will need to implement the UITableViewDelegate method - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *text = [self getItemForKey:kSummary];
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    //You will need to define kDefaultCellFont
    CGSize labelSize = [text sizeWithFont:kDefaultCellFont 
                        constrainedToSize:constraintSize 
                            lineBreakMode:UILineBreakModeWordWrap];
    return labelSize.height + ANY_OTHER_HEIGHT;
}