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

一、获取字符串的高度

- (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-获取字符串、富文本的高度)