美文网首页
iOS计算富文本(NSMutableAttributedStri

iOS计算富文本(NSMutableAttributedStri

作者: 啸狼天 | 来源:发表于2021-12-21 15:12 被阅读0次

有时候开发中我们为了样式好看, 需要对文本设置富文本属性, 设置完后那么怎样计算其高度呢, 很简单, 方法如下:

- (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;
}

相关文章

网友评论

      本文标题:iOS计算富文本(NSMutableAttributedStri

      本文链接:https://www.haomeiwen.com/subject/qfexqrtx.html