如何根据标签的高度动态调整UITableViewCell的大小?

时间:2011-07-14 21:46:59

标签: iphone objective-c uitableview

我有一个分组的UITableView。

我正在覆盖表行高度,但我希望第一行的动态高度基于单元格中Label的高度大小。我怎样才能达到这个高度?

{
    CGFloat rowHeight = 0;

    if(indexPath.section == kBioSection) {
        switch(indexPath.row) {
            case kBioSectionDescriptionRow:                 
                rowHeight = 100;
                break;
            case kBioSectionLocationRow:                    
                rowHeight = 44;
                break;
            case kBioSectionWebsiteRow:                 
                rowHeight = 44;
                break;
        }
    }
    else {
        rowHeight = 44;
    }

    return rowHeight;
}

3 个答案:

答案 0 :(得分:2)

NSString有一个名为

的方法
- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode;

UIStringDrawing.h

中声明

它将为您提供绘制该字符串所需的大小。

您可以获得所需尺寸的高度,并添加您想要的任何其他内容,例如其他标签/视图以及它们之间的空间,以计算最终高度。

这样的事情:

{
    CGFloat rowHeight = 0;

    if(indexPath.section == kBioSection) {
        switch(indexPath.row) {
            case kBioSectionDescriptionRow:                 
                CGSize labelSize = [descriptionText sizeWithFont:labelFont forWidth:tableView.frame.size.width - 20 lineBreakMode:UILineBreakModeWordWrap]; //Assuming 10 px on each side of the label
                rowHeight = labelSize + 50; //Assuming there are 50 px of extra space on the label, besides the text
                break;
            case kBioSectionLocationRow:                    
                rowHeight = 44;
                break;
            case kBioSectionWebsiteRow:                 
                rowHeight = 44;
                break;
        }
    }
    else {
        rowHeight = 44;
    }

    return rowHeight;
}

答案 1 :(得分:2)

请浏览以下链接:

http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/ - 本教程清楚地向您解释如何动态增加UITableViewCell高度。

答案 2 :(得分:1)

你可以使用

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
 {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:15.0];
}

设置单元格的高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellText = @"Go get some text for your cell.";
UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:15.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

return labelSize.height + 20;//set as per your need
}
相关问题