zoukankan      html  css  js  c++  java
  • 获取指定<文字行数>的<高度>是多少 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 就是两行文字所占的高度
  • 相关阅读:
    RabbitMQ学习系列二:.net 环境下 C#代码使用 RabbitMQ 消息队列
    越狱Season 1- Episode 22: Flight
    越狱Season 1-Episode 21: Go
    越狱Season 1-Episode 20: Tonight
    越狱Season 1-Episode 19: The Key
    越狱Season 1- Episode 18: Bluff
    越狱Season 1-Episode 17: J-Cat
    越狱Season 1- Episode 16
    越狱Season 1-Episode 15: By the Skin and the Teeth
    越狱Season 1-Episode 14: The Rat
  • 原文地址:https://www.cnblogs.com/daxueshan/p/9245343.html
Copyright © 2011-2022 走看看