美文网首页
ios计算UILabel的高度(带有行间距的情况)

ios计算UILabel的高度(带有行间距的情况)

作者: 透支未来 | 来源:发表于2016-09-05 15:33 被阅读54次
    -(void)setLabelSpace:(UILabel*)label withValue:(NSString*)str withFont:(UIFont*)font {
        NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
        paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
        paraStyle.alignment = NSTextAlignmentLeft;
        paraStyle.lineSpacing = 5; //设置行间距
        paraStyle.hyphenationFactor = 1.0;
        paraStyle.firstLineHeadIndent = 0.0;
        paraStyle.paragraphSpacingBefore = 0.0;
        paraStyle.headIndent = 0;
        paraStyle.tailIndent = 0;
        //设置字间距 NSKernAttributeName:@1.5f
        NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f};
        
        NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithString:str attributes:dic];
        label.attributedText = attributeStr;
    }
    
    
    -(CGFloat)getSpaceLabelHeight:(NSString *)str withFont:(UIFont*)font withWidth:(CGFloat)width {
        NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
        paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
        paraStyle.alignment = NSTextAlignmentLeft;
        paraStyle.lineSpacing = 0;
        paraStyle.hyphenationFactor = 1.0;
        paraStyle.firstLineHeadIndent = 0.0;
        paraStyle.paragraphSpacingBefore = 0.0;
        paraStyle.headIndent = 0;
        paraStyle.tailIndent = 0;
        NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f
                              };
        ```
        CGSize size = [self.labelBody.text boundingRectWithSize:CGSizeMake(SCREENWIDTH-40, 2000) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]} context:nil].size;
        
        return size.height;
    }

    相关文章

      网友评论

          本文标题:ios计算UILabel的高度(带有行间距的情况)

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