UILabel如何根据富⽂本内容计算⾼度
⽅法1:
(第⼀段代码和法2第⼀段相同)
NSString *str = @"这是⼀个有关富⽂本的⼀个记录,希望能帮助⼀些刚刚⼊⾏不久的同⾏们⼀起进步,让⼤家都能躺仰的iOS代码的世界⾥,尽情享受"; NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:str];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.lineSpacing = 10;
UIFont *font = [UIFont systemFontOfSize:20];
[attributeString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, str.length)];
[attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, str.length)];
NSStringDrawingOptions options = NSStringDrawingUsLineFragmentOrigin | NSStringDrawingUsFontLeading;
CGRect labelRect = [attributeString boundingRectWithSize:CGSizeMake(688, CGFLOAT_MAX) options:options context:nil];
NSLog(@"size:%@", NSStringFromCGSize(labelRect.size));
_contentLabel.attributedText = attributeString;
_contentLabel.frame = CGRectMake(40, _titleLabel.frame.size.height+_igin.y+15, labelRect.size.width, labelRect.size.height);
⽅法2:
(第⼀段代码和法1第⼀段相同)
NSString *str = @"这是⼀个有关富⽂本的⼀个记录,希望能帮助⼀些刚刚⼊⾏不久的同⾏们⼀起进步,让⼤家都能躺仰的iOS代码的世界⾥,尽情享受"; NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:str];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.lineSpacing = 10;
UIFont *font = [UIFont systemFontOfSize:20];
[attributeString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, str.length)];
[attributeString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, str.length)];
//1.计算label的⾼度
//textRect..⽅法可以根据指定的最⼤区域
//计算⽂本最终占据的实际的空间⼤⼩
CGRect textOfRect = [lf.contentLabel textRectForBounds:CGRectMake(0, 0, 688, CGFLOAT_MAX) limitedToNumberOfLines:0];
//根据label的⼤⼩计算label的frame
_contentLabel.attributedText = attributeString;
_contentLabel.frame = CGRectMake(40, _titleLabel.frame.size.height+_igin.y, textOfRect.size.width, textOfRect.size.height);