iOS 根据字符串计算label高度

_decriptionLab = [[UILabel alloc] init];

    [self.view addSubview:_decriptionLab];

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

    [style setLineSpacing:16];

    NSString *tipStr = [NSString stringWithFormat:@"      %@",_decription];

    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:16.0], NSParagraphStyleAttributeName:style};

    NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:tipStr attributes:dic];

    _decriptionLab.attributedText = attributeStr;

    _decriptionLab.numberOfLines = 0;

    CGFloat height = [self getHeightLineWithString:tipStr withWidth:kScreenWidth-30 withFont:[UIFont systemFontOfSize:16.0]];

    _decriptionLab.frame = CGRectMake(15, 70, kScreenWidth-30, height);

 

#pragma mark - 根据字符串计算label高度

- (CGFloat)getHeightLineWithString:(NSString *)string withWidth:(CGFloat)width withFont:(UIFont *)font {

    

    //1.1最大允许绘制的文本范围

    CGSize size = CGSizeMake(width, 2000);

    //1.2配置计算时的行截取方法,和contentLabel对应

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

    [style setLineSpacing:16];

    //1.3配置计算时的字体的大小

    //1.4配置属性字典

    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:style};

    //2.计算

    //如果想保留多个枚举值,则枚举值中间加按位或|即可,并不是所有的枚举类型都可以按位或,只有枚举值的赋值中有左移运算符时才可以

    CGFloat height = [string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size.height;

    

    return height;

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值