UITableViewCell和heightForRowAtIndexPath的iOSdynamic高度

我在一个大项目中使用Autolayout来处理新的UITableViewCells。

我有一个TableView自动计算每一行的高度,那里我不使用委托函数heightForRowAtIndexPath

我已经宣布了估计的行高:

 tableView.estimatedRowHeight = 44.0 tableView.rowHeight = UITableViewAutomaticDimension 

我的问题是:在另一个TableViewController有很多的UITableViewCells,我在编程上需要声明heightForRowAtIndexPath单元格的高度。 我知道这将是更好的转换所有单元格使用独特的解决scheme,但在这个项目中有很多不同的单元格,所以我想使用一个解决方法,并结合dynamic计算的高度与自动布局和编程计算的行高度。

这可能吗?

如果您使用的是iOS 8或更高版本,则不需要dynamic计算高度。 自动布局将为您做所有的事情。 但是如果你使用低于IOS 8,你需要计算细胞高度。

对于IOS 8:

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return UITableViewAutomaticDimension; } 

并在控制器中添加以下代码:

 tableView.estimatedRowHeight = 400.0 tableView.rowHeight = UITableViewAutomaticDimension 

estimatedRowHeight高度应该是最高的高度,可以为您的细胞。

谢谢

使用boundingRectWithSizedynamic计算内容的高度。 如果你有一个dynamic的UILabel ,你可以使用下面的代码:

 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { /* Check Content Size and Set Height */ CGRect answerFrame = [YOUR_LABEL.text boundingRectWithSize:CGSizeMake(240.f, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:[UIFont fontWithName:@"" size:14.0f]} context:nil]; CGSize requiredSize = answerFrame.size; return requiredSize.height; } 

你可以试试这个

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { int topPadding = cell.yourLabel.frame.origin.x; int bottomPadding = cell.frame.size.heigth-(topPadding+cell.yourLabel.frame.size.height); NSString *text = [DescArr objectAtIndex:[indexPath row]]; CGSize maximumSize = CGSizeMake(cell.yourLabel.frame.size.width, 9999); CGSize expectedSize = [text sizeWithFont:yourCell.yourLabel.font constrainedToSize:maximumSize lineBreakMode:yourCell.yourLabel.lineBreakMode]; return topPadding+expectedSize.height+bottomPadding; }