美文网首页
iOS 根据字符串计算label高度

iOS 根据字符串计算label高度

作者: YJLJianShu | 来源:发表于2018-04-23 11:33 被阅读0次
    tipLabel = [[UILabel alloc] init];  
        [self.backScrollView addSubview:tipLabel];  
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];  
        [style setLineSpacing:10];  
        NSString *tipStr = @"温馨提示:这是要计算高度的字符串";  
        NSDictionary *dic = @{NSFontAttributeName:kSystemFont_16, NSParagraphStyleAttributeName:style};  
        NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:tipStr attributes:dic];  
        tipLabel.attributedText = attributeStr;  
        tipLabel.numberOfLines = 0;  
        CGFloat height = [self getHeightLineWithString:tipStr withWidth:kDeviceWidth - 20 withFont:kSystemFont_16];  
        tipLabel.frame = CGRectMake(10, topHeight + 300, kDeviceWidth - 20, 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:10];  
        //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;  
    }  

相关文章

网友评论

      本文标题:iOS 根据字符串计算label高度

      本文链接:https://www.haomeiwen.com/subject/ctiklftx.html