计算文字高度或宽度

创建一个NSString类目

1、计算文字高度

- (CGFloat)heightWithFont:(UIFont *)font fixedWithWidth:(CGFloat)width {

    CGRect rect = [self boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    
    return ceil(rect.size.height);
}

2、计算文字宽度

- (CGFloat)widthWithFont:(UIFont *)font fixedWithHeight:(CGFloat)height {
     
    CGRect rect = [self boundingRectWithSize:CGSizeMake(MAXFLOAT, height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    
    return ceil(rect.size.width);
}

你可能感兴趣的:(计算文字高度或宽度)