动态调整UITableViewCell到UILabel的高度

问题描述:

我想根据文本根据标签的高度和标签的高度来调整单元格的高度。或者有什么办法可以根据在UITextView中输入的文字来调整单元格的高度?动态调整UITableViewCell到UILabel的高度

+0

你是说你想调整包含UITextView的UITableViewCell的大小,因为更多的文本输入到文本视图? – teabot 2009-06-18 12:47:23

+0

不,先生我有一个自定义单元格与cell.and文本标签来自数据库。 我如何增加单元格行高度和标签no行或标签高度,以便长文本可以适合单元格的标签 – 2009-06-21 06:22:18

+0

可能重复[变量UITableCellView高度与子视图](http://stackoverflow.com/questions/128012/ variable-uitablecellview-height-with-subview) – outis 2012-07-14 20:28:23

此方法在iOS 7.0以上版本中被破坏。

有一个UITableView委托方法称为heightForRowAtIndexPath,在创建单元格或表之前调用。

你可以使用传递给它的NSIndexPath获得在特定行的文本,并使用sizeWithFont方法从UIStringDrawing.h来计算该行的CGSize

例如:

CGSize size = [text sizeWithFont:font 
        constrainedToSize:maximumLabelSize 
        lineBreakMode:UILineBreakModeWordWrap]; 

最后,你将返回size.height

──为iOS7--

立足这一关乔什维拉的回答...把这个在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 < 7,但我相信它应该为正常工作。