计算YYLabel
内容富文本(带行间距)attributeStr
的高度,假设行间距间距是5
,走的弯路:
一、根据内容求高度
/// 带有行间距求高度 假如是行间距是5
- (CGRect)boundsWithFont:(UIFont *)font text:(NSString *)text needWidth:(CGFloat)needWidth lineSpacing:(CGFloat )lineSpacing
{
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:text];
// 样式
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.lineSpacing = lineSpacing; // 行间距
style.lineBreakMode = NSLineBreakByWordWrapping;
// 样式
[attributeString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, text.length)];
// 文字大小
[attributeString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:textFontValue15] range:NSMakeRange(0, text.length)];
NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
CGRect rect = [attributeString boundingRectWithSize:CGSizeMake(needWidth, CGFLOAT_MAX) options:options context:nil];
return rect;
}
二、 YYLabel
赋值NSString
->NSAttributedString
(带行间距)
/// 设置行间距的NSAttributedString赋值给YYLabel
- (NSAttributedString *)matchesAttributedString:(NSString *)str{
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
// 间距
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:5.0]; // 行间距假如是5
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
[attrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [str length])];
[attrStr addAttribute:NSForegroundColorAttributeName value:UIColorFromHEX(0x242831) range:NSMakeRange(0, attrStr.length)];
[attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:textFontValue15] range:NSMakeRange(0, attrStr.length)];
return attrStr;
}
当文本比较多的时候展示出的空白比较多,根据观察是展示的行间距小于5.0
,所以整体偏中聚集,上下留白较多。但是对于UILabel
是没有问题的。
三、3.1 对于YYLabel
正确的做法是如下所示:
// 计算文本尺寸YYTextLayout
CGSize maxSize = CGSizeMake(fixWidth, MAXFLOAT);
YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:maxSize text:self.contentLbl.attributedText];
self.contentLbl.textLayout = layout;
CGFloat introHeight = layout.textBoundingSize.height;
self.contentLbl.width = maxSize.width;
// 记录真正的正确高度
contentH = introHeight;
3.2 不借助控件求高度:
CGSize maxSize = CGSizeMake(fixWidth, MAXFLOAT);
//计算文本尺寸
YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:maxSize text:[self matchesAttributedString:@"普通文本内容"]];
CGFloat introHeight = layout.textBoundingSize.height;
contentH = introHeight; // 高度
注:matchesAttributedString:
自定义的方法,NSString
->NSAttributedString
见上文