我正在尝试为表格中的单元格设置动态高度,高度应基于文本长度和最大宽度。
当此文本出现在一行中,没有行分隔符时,就会出现问题。不管文本有多大,如果没有行分隔符,它会检测到文本适合单行,因此我的单元格高度不会增加。
难道我做错了什么?我怎样才能实现它?谢谢。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat cellheight = 35.0f; // BASE
NSString *text = @"...";
if (text) {
UIFont *font = (indexPath.row == 0) ? [UIFont systemFontOfSize:14] : [UIFont systemFontOfSize:12];
CGSize constraintSize = CGSizeMake(self.tableView.frame.size.width, CGFLOAT_MAX);
if (IS_EARLIER_THAN_IOS7) {
CGSize size = [text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:NSLineBreakByCharWrapping];
cellheight += size.height;
} else {
CGSize size = [text sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12.0f]}];
CGSize adjustedSize = CGSizeMake(ceilf(size.width), ceilf(size.height));
cellheight += adjustedSize.height;
}
return (indexPath.row == 0) ? cellheight + 40.0f : cellheight;
}
}