获取指定<文字行数>的<高度>是多少 TextKit

- (CGSize)maxLineSizeWithLines:(NSInteger)lines constraintSize:(CGSize)size attributes:(NSDictionary*)dicAttr
{
  //负责布局渲染 NSLayoutManager
* manager = [[NSLayoutManager alloc] init];
  //指定渲染的区域 NSTextContainer
* con = [[NSTextContainer alloc] initWithSize:size]; con.lineFragmentPadding = 0; //行间距 con.maximumNumberOfLines = lines;//最多显示的行数 [manager addTextContainer:con];
  //负责存储文字内容 NSTextStorage
* storage = [[NSTextStorage alloc] initWithString:_str]; [storage addLayoutManager:manager]; [storage addAttributes:dicAttr range:NSMakeRange(0, _str.length)]; CGRect rt = [manager boundingRectForGlyphRange:NSMakeRange(0, _str.length) inTextContainer:con]; return rt.size; }

//下面是测试代码
 UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200, kWidth, 100)];
    label.backgroundColor = [UIColor greenColor];
    label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:label];
    
     _str = @"啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊";
    
    label.text = _str;
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
    style.lineSpacing = 0;
    
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:15],NSParagraphStyleAttributeName:style};
    
    CGSize size = [self maxLineSizeWithLines:2 constraintSize:CGSizeMake(kWidth, 200) attributes:dic];
    
    NSLog(@"%@",NSStringFromCGSize(size));
    
    label.height = size.height;  //返回的size 就是两行文字所占的高度
原文地址:https://www.cnblogs.com/daxueshan/p/9245343.html