計(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)文本比較多的時(shí)候展示出的空白比較多,根據(jù)觀察是展示的行間距小于5.0
林说,所以整體偏中聚集煎殷,上下留白較多。但是對(duì)于UILabel
是沒有問題的腿箩。
三豪直、3.1 對(duì)于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
見上文