計(jì)算YYLabel內(nèi)容富文本(帶行間距)attributeStr的高度,假設(shè)行間距間距是5,走的彎路:
一、根據(jù)內(nèi)容求高度
/// 帶有行間距求高度 假如是行間距是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(帶行間距)
/// 設(shè)置行間距的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;
}
當(dāng)文本比較多的時候展示出的空白比較多,根據(jù)觀察是展示的行間距小于5.0,所以整體偏中聚集,上下留白較多。但是對于UILabel是沒有問題的。
三、3.1 對于YYLabel正確的做法是如下所示:
// 計(jì)算文本尺寸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);
//計(jì)算文本尺寸
YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:maxSize text:[self matchesAttributedString:@"普通文本內(nèi)容"]];
CGFloat introHeight = layout.textBoundingSize.height;
contentH = introHeight; // 高度
注:matchesAttributedString:自定義的方法,NSString->NSAttributedString見上文