UILabel在设置了行间距和字间距后计算高度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
- (CGFloat)textHeightFromTextString:(NSString *)text width:(CGFloat)textWidth fontSize:(CGFloat)textSize {

//设置行间距
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:3];

//把行间距和字间距加入高度计算的方法
NSDictionary*attrs =@{NSFontAttributeName: [UIFont systemFontOfSize:textSize],NSParagraphStyleAttributeName:paragraphStyle,NSKernAttributeName:@1.5f};

CGRect rect = [text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingTruncatesLastVisibleLine attributes:attrs context:nil];

//返回计算出的行高
return ceilf(rect.size.height);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
UILabel *msgLab = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, frame.size.width-30, 100)];
msgLab.backgroundColor = [UIColor clearColor];
msgLab.textColor = [[UIColor whiteColor] colorWithAlphaComponent:.8];
msgLab.numberOfLines = 0;
msgLab.lineBreakMode = NSLineBreakByWordWrapping;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[bannerDic objectForKey:@"msgText"]];

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:3];//调整行间距
//这个设置在字体无法显示时一省略号表示
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;

[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attributedString length])];

[attributedString addAttribute:NSFontAttributeName value:msgFont range:NSMakeRange(0, attributedString.length)];
msgLab.attributedText = attributedString;
[self addSubview:msgLab];