dynamic调整UITableViewCell到UILabel的高度

我想根据标签的高度和标签的高度来调整单元格的高度。 或者有什么办法可以根据在UITextViewinput的文本来调整单元格的高度?

这个方法在iOS 7.0以后被破坏。

在创build单元格或表之前调用了一个名为heightForRowAtIndexPathUITableView委托方法。

您可以使用传递给它的NSIndexPath来获取特定行的文本,并使用UIStringDrawing.hsizeWithFont方法计算该行的CGSize

例如:

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

最后你会返回size.height

– 对于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; } 

我还没有testing它的iOS <7,但我相信它应该为此工作。