UILabel设置行间距,计算文本高度

UILabel *labelContent = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth - 30, 4000)];
        
// 调整行间距
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:content];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:10];
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [content length])];
labelContent.attributedText = attributedString;
        
//labelContent.text = content;
labelContent.font = [UIFont systemFontOfSize:15 weight:0];
labelContent.numberOfLines = 0;
labelContent.textColor = COLOR(@"#3C3C3C");
CGRect framelabel = labelContent.frame;

//计算高度
framelabel.size = [self getSpaceLabelHeight:labelContent.text withFont:labelContent.font withWidth:labelContent.frame.size.width];
        labelContent.frame = framelabel;

计算高度

-(CGSize)getSpaceLabelHeight:(NSString*)str withFont:(UIFont*)font withWidth:(CGFloat)width {
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paraStyle.alignment = NSTextAlignmentLeft;
    paraStyle.lineSpacing = 10;
    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:@0
                          };
    
    CGSize size = [str boundingRectWithSize:CGSizeMake(width, 4000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return size;
}

原文

其他

你可能感兴趣的:(UILabel设置行间距,计算文本高度)