dynamic改变UITable细胞高度?

我需要根据内容大小/长度调整单元格高度。尝试了几种方法,哪一种给出的确切高度没有重叠?

看到这个教程更改UITableViewCell高度dynamic..

调整-A-的UITableViewCell

也使用这个教程..

UITableViewCell的dynamic高度

还可以使用tableView:heightForRowAtIndexPath:方法来设置单元格的高度与indexpath

这是从我以前的答案 – 自定义UITableViewCell的高度 :

使用此方法获取文本的文本高度

 -(CGFloat)getLabelHeightForText:(NSString *)text andWidth:(CGFloat)labelWidth { CGSize maximumSize = CGSizeMake(labelWidth, 10000); //provide appropriate font and font size CGSize labelHeighSize = [text sizeWithFont: [UIFont fontWithName:@"Trebuchet MS" size:13.0f] constrainedToSize:maximumSize lineBreakMode:UILineBreakModeTailTruncation]; return labelHeighSize.height; } 

此方法将返回您传递的文本的高度。 在你的class级中添加这个方法。 并使用tableView:heightForRowAtIndexPath:委托方法来设置每个单元格的高度

 -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { Feedback *item = [self.items objectAtIndex:indexPath.row]; CGFloat textHeight = [self getLabelHeightForText:item.comment andWidth:162];//give your label width here return textHeight; } 

示例,您可以编辑并尝试

  - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { NSDictionary *itemAtIndex = (NSDictionary *)[chatQuestions objectAtIndex:indexPath.row]; if ([self sizeForText:[itemAtIndex objectForKey:@"text"]].height+20>50) { return [self sizeForText:[itemAtIndex objectForKey:@"text"]].height+20; } else{ return 50;} } -(CGSize)sizeForText:(NSString*)text { CGSize constraintSize; constraintSize.width = 190.0f; constraintSize.height = MAXFLOAT; UIFont *labelFont = [UIFont fontWithName:@"Noteworthy-Light" size:18]; CGSize stringSize =[text sizeWithFont:labelFont constrainedToSize: constraintSize lineBreakMode: UILineBreakModeWordWrap]; return stringSize; } 
 //Calculate the expected size based on the font and linebreak mode of your label CGSize maximumLabelSize = CGSizeMake(296,9999); CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode]; //adjust the label the the new height. CGRect newFrame = yourLabel.frame; newFrame.size.height = expectedLabelSize.height; yourLabel.frame = newFrame; 

在你的情况下,你需要根据标签设置单元格的高度。

检查链接:

http://dcraziee.wordpress.com/2013/05/22/calculate-size-of-uillabel-base-on-text-in/

有一个名为的函数

 -(CGFloat)getHeightForLabel:(NSString *)_str font:(UIFont *)fontOfObject 

使用该函数来计算高度:

 -(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { CGFloat _height = [self getHeightForLabel:self.label.text font:[self.label font]]; return _height; }