有时候开发中我们为了样式好看, 需要对文本设置富文本属性, 设置完后那么怎样计算其高度呢, 很简单, 方法如下:
- (CGFloat)calculateHeightWithTitle:(NSString *)title Content:(NSString *)content Score:(NSString *)score Font:(UIFont *)font width:(CGFloat)width{
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
//style.lineBreakMode = NSLineBreakByCharWrapping;
style.alignment = NSTextAlignmentLeft;
style.lineSpacing = 4; // 字体的行间距
style.headIndent = 0; // 行首缩进
style.paragraphSpacing = 4; // 段与段之间的间距
/// 字体大小17号字乘以2,34f即首行空出2字符
style.firstLineHeadIndent = AutoFont(12).pointSize * 2;//首行缩进
NSString *space = @" ";
if (title.length == 0) {
space = @"";
}
NSMutableAttributedString *strAtt = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@%@ (共 %@ 分)", kIfNull(title), space, content, score]];
[strAtt addAttribute:NSFontAttributeName value:AutoFont(12) range:NSMakeRange(0, strAtt.length)];
NSRange range = NSMakeRange(0, title.length);
[strAtt addAttribute:NSFontAttributeName value:AutoFont(14) range:range];
NSRange range2 = NSMakeRange(strAtt.length-score.length-4, score.length+2);
[strAtt addAttribute:NSFontAttributeName value:AutoBlodFont(14) range:range2];
[strAtt addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, strAtt.length)];
CGSize size = [strAtt boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
return size.height + 1;
}
网友评论