将UITableViewCell的大小动态调整为UILabel的高度

时间:2009-06-18 12:26:37

标签: ios objective-c uitableview math

我想根据标签的高度和标签的高度调整单元格的高度。或者有什么方法可以根据UITextView中输入的文字调整单元格的高度?

2 个答案:

答案 0 :(得分:17)

自iOS 7.0以来,这种方法已被弃用。

在创建单元格或表格之前,有一个名为UITableView的{​​{1}}委托方法。

您可以使用传递给它的heightForRowAtIndexPath来获取特定行的文字,并使用NSIndexPath中的sizeWithFont方法计算该行的UIStringDrawing.h

例如:

CGSize

最后你会返回CGSize size = [text sizeWithFont:font constrainedToSize:maximumLabelSize lineBreakMode:UILineBreakModeWordWrap];

答案 1 :(得分:6)

- 适用于iOS7 -

基于Josh Vera的答案......将其置于heightForRowAtIndexPath。

我的表数据存储在NSArray * tableData中。

// set the desired width of the textbox that will be holding the adjusted text, (for clarity only, set as property or ivar)
CGFloat widthOfMyTexbox = 250.0;

-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Get a reference to your string to base the cell size on.
    NSString *cellText = [self.tableData objectAtIndex:indexPath.row];
    //set the desired size of your textbox
    CGSize constraint = CGSizeMake(widthOfMyTextBox, MAXFLOAT);
    //set your text attribute dictionary
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:14.0] forKey:NSFontAttributeName];
    //get the size of the text box
    CGRect textsize = [cellText boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
    //calculate your size
    float textHeight = textsize.size.height +20;
    //I have mine set for a minimum size
    textHeight = (textHeight < 50.0) ? 50.0 : textHeight;

    return textHeight;
}

我还没有针对iOS&lt; 7进行测试,但我相信它也适用于此。