1、计算UILabel占用的Size
+ (CGSize)wsg_estimateSizeOfText:(NSString *)text withMaxWidth:(CGFloat)maxWidth font:(UIFont *)font LineSpace:(CGFloat)lineSpace {
NSMutableDictionary *attrDic = [NSMutableDictionary new];
attrDic[NSFontAttributeName] = font;
if (lineSpace > 0) {
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:lineSpace];
attrDic[NSParagraphStyleAttributeName] = paragraphStyle;
}
CGSize labelSize = [text boundingRectWithSize:CGSizeMake(maxWidth, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attrDic
context:nil].size;
return labelSize;
}
2、动态修改UILabel的行高
- (void)wsg_setTextLineSpacing:(NSString*)text lineSpacing:(CGFloat)lineSpacing {
if (!text || lineSpacing < 0.01) {
self.text = text;
return;
}
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:lineSpacing]; //设置行间距
[paragraphStyle setLineBreakMode:self.lineBreakMode];
[paragraphStyle setAlignment:self.textAlignment];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])];
self.attributedText = attributedString;
}
网友评论