根据UILabel的高度设置UITableViewCell的高度

时间:2011-04-15 20:47:27

标签: iphone objective-c uitableview height uilabel

如果您能告诉我如何根据UILabel的高度设置UITableViewCell的高度,我将非常感激。

我目前设置UILabel高度的代码是:

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 个答案:

答案 0 :(得分:5)

您需要实现UITableViewDelegate方法- (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;
}