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 就是两行文字所占的高度
  • 相关阅读:
    Jconsole连接远程服务器
    limesurvey设置短调查问卷url
    centos7 安装R和Rstudio客户端
    p便签,去掉首行缩进
    linux mint运行docker
    Kafka高可用实现
    利用ZooKeeper简单实现分布式锁
    如何判断一个数是否在40亿个整数中?
    稀疏矩阵乘法
    Java 软引用和弱引用
  • 原文地址:https://www.cnblogs.com/daxueshan/p/9245343.html
Copyright © 2011-2022 走看看