美文网首页
iOS开发带行间距和多换行的字符串高度

iOS开发带行间距和多换行的字符串高度

作者: 稻草人12138 | 来源:发表于2020-04-22 10:39 被阅读0次

实际开发中我们经常会遇到根据文字多少计算label高度的问题,一般的情况可以设定label高度自适应,再拿到适应后的高度就可以了。

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 20)];;
label.text = @"xxx";
[label sizeToFit];
CGFloat height = label.height;

但是些情况下该方法并不好用,比如字符串要求有行间距,并且有很多个换行符的情况下就会出现计算不准的问题,可以使用

+(CGFloat)getSpaceLabelHeight1:(NSString *)str withFontValue:(NSInteger)fontvalue withWidth:(CGFloat)width lineSpace:(NSInteger) linespace{
     CGSize textSize = CGSizeZero;
     // 多行必需使用NSStringDrawingUsesLineFragmentOrigin,网上有人说不是用NSStringDrawingUsesFontLeading计算结果不对
     NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
     NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
     [style setLineBreakMode:NSLineBreakByCharWrapping];
     style.lineSpacing = linespace; // 设置行间距
     NSDictionary *attributes = @{ NSFontAttributeName : [UIFont systemFontOfSize:fontvalue], NSParagraphStyleAttributeName : style };
         CGRect rect = [str boundingRectWithSize:(CGSize){ width, MAXFLOAT}
                                                 options:opts
                                              attributes:attributes
                                                 context:nil];
     textSize = rect.size;
    return textSize.height;
}

相关文章

网友评论

      本文标题:iOS开发带行间距和多换行的字符串高度

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