iOS 计算文本的高度
下列方法能够比较简单的计算文本的高度,其中kSystemMessageCellEdgSize等为自定义的static 变量。其中页添加了测试用的数据,希望多多注意!!!
+ (CGFloat)computeCellHeight:(CGFloat)width item:(HDBSystemMessage *)item
{
CGFloat height = kSystemMessageCellEdgeSize * 2.0f + kSystemMessageCellBottomLineHeight + 13.0f;
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
paragraphStyle.lineSpacing = kSystemMessageCellContentLineSpace;
NSDictionary *attributes = @{
NSFontAttributeName: [UIFont systemFontOfSize:FontSize3],
NSParagraphStyleAttributeName: paragraphStyle
};
#ifdef TextDebug
NSString *str1 = @"测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试";
CGRect rect = [str1 boundingRectWithSize:CGSizeMake(width - kSystemMessageCellEdgeSize * 2.0f, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
#else
CGRect rect = [item.summary boundingRectWithSize:CGSizeMake(width - kSystemMessageCellEdgeSize * 2.0f, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
#endif
height += rect.size.height;
#ifdef TextDebug
NSString *str2 = @"测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试";
rect = [str2 boundingRectWithSize:CGSizeMake((width - kSystemMessageCellEdgeSize * 2.0f) * 2.0f / 3.0f, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
#else
rect = [item.title boundingRectWithSize:CGSizeMake((width - kSystemMessageCellEdgeSize * 2.0f) * 2.0f / 3.0f, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
#endif
height += rect.size.height;
if (item.imageUrl != nil && ![item.imageUrl isEqualToString:@""]) {
height += (width - kSystemMessageCellEdgeSize * 2.0f) / 16.0f * 9.0f + kSystemMessageCellEdgeSize;
}
if (item.url != nil && ![item.url isEqualToString:@""]) {
height += 13.0f + FontSize4;
}
return height;
}