在使用label显示文字时,会出现只显示一行内容的情况,此时需要设置根据内容和字号判断尺寸。
核心代码如下:
//获取内容
CommentModel *model = self.data[indexPath.row];
NSString *content = model.content;
//属性字典
NSDictionary *attributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:17] };
//根据内容和字号判断尺寸
/*
rectWithSize:
width:label的实际宽度
height:label的最大高度(如果超出这个高度,剩余文字会以省略号的形式出现)
options:NSStringDrawingUsesLineFragmentOrigin 忽略该选项
attributes:属性字典
*/
//根据约束计算:123
// 8+77+8+( labelWidth+8+14)+8 = tableViewWidh
CGRect rect = [content boundingRectWithSize:CGSizeMake(tableView.frame.size.width-123, 1000)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
//根据约束计算:58
//8+(8+24+8+2+labelHeight)+8 =cellHeight
//10:微调
CGFloat cellHeight = rect.size.height+58+10;
if (cellHeight < 110) {
cellHeight = 110;
}
return cellHeight;
}
return 110;