美文网首页很常
iOS-获取字符串、富文本的高度

iOS-获取字符串、富文本的高度

作者: zwing | 来源:发表于2021-03-25 10:40 被阅读0次

    一、获取字符串的高度

    - (CGFloat)getStringHeightWithText:(NSString *)string width:(CGFloat)width font:(UIFont *)font {
        CGSize size = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil].size;
        return size.height;
    }
    
    

    二、获取富文本的高度

    方法一:
    - (CGFloat)getAttributedStringHeightWithText:(NSAttributedString *)attributedString width:(CGFloat)width font:(UIFont *)font {
        static UILabel *stringLabel = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            stringLabel = [[UILabel alloc] init];
            stringLabel.numberOfLines = 0;
        });
        stringLabel.font = font;
        stringLabel.attributedText = attributedString;
        return [stringLabel sizeThatFits:CGSizeMake(width, MAXFLOAT)].height;
    }
    
    方法二:
    - (CGFloat)getAttributedStringHeightWithText:(NSAttributedString *)attributedString width:(CGFloat)width {
        // 字号在计算高度之前设置
        CGSize size = [attributedString boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
        return size.height;
    }
    

    相关文章

      网友评论

        本文标题:iOS-获取字符串、富文本的高度

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