UITableViewCell和heightForRowAtIndexPath的iOS动态高度
问题描述:
我在大型项目中使用Autolayout来创建新的UITableViewCells。UITableViewCell和heightForRowAtIndexPath的iOS动态高度
我有一个TableView,其中每行的高度自动计算,我不使用委托功能heightForRowAtIndexPath
。
我声明了一个估计行高度:
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
我的问题是:在另一个TableViewController有很多UITableViewCells,在那里我编程需要声明细胞的高度heightForRowAtIndexPath
的。我知道将所有单元格转换为独特的解决方案会更好,但在此项目中有很多不同的单元格,所以我想使用一种解决方法并将动态计算的高度与自动布局以及编程计算的行高度。
这可能吗?
答
如果您使用的是iOS 8或更高版本,则无需动态计算高度。自动布局将为您做所有事情。但是如果你使用的是低于IOS 8,你需要计算细胞高度。
对于IOS 8:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewAutomaticDimension;
}
并添加下面的代码在你的控制器:
tableView.estimatedRowHeight = 400.0
tableView.rowHeight = UITableViewAutomaticDimension
凡estimatedRowHeight
应该是最大高度可以为您的细胞。
谢谢
答
使用boundingRectWithSize
动态计算内容的高度。 如果你有一个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;
}
真棒谢谢。 –