如何计算NSAttributeString和NSString的label高度

2025-02-23 22:16:07
推荐回答(1个)
回答1:

uilabel *label = [[uilable alloc]initWithFrame:frame];
label.numberOfLines = 0;//任意行数
//以下方法可以插入行间距。如果用label.text就不能插入行距,很难看。
NSString text = @"xxxx";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

//注意,每一行的行间距分两部分,topSpacing和bottomSpacing。

[paragraphStyle setLineSpacing:3.f];//调整行间距

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

self.attributedText = attributedString;//ios 6

CGSize size = [self sizeThatFits:CGSizeMake(label.frame.size.width, MAXFLOAT)];

CGRect frame = label.frame;

frame.size.height = size.height;

[label setFrame:frame];
//大功告成。在固定label宽度条件下,自动调整行数、高度。