最近做项目的时候总是找不到很好的方法去获取到文本或者富文本的高度,因为富文本有可能会带上图片等各种情况,导致很难获取到精确正确的文本高度。
查了很多方法,然后发现可以直接利用 UILabel 来获取文本或者富文本的高度。
这里使用的是分类的方法
富文本版本
#import "NSAttributedString+Ectension.h"
@implementation NSAttributedString (Ectension)
- (CGFloat)getHeightByWidth:(CGFloat)width {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 0)];
label.attributedText = self;
label.numberOfLines = 0;
[label sizeToFit];
CGFloat height = label.frame.size.height;
return ceil(height);
}
@end
纯文字版本
#import "NSString+Extension.h"
@implementation NSString (Extension)
- (CGFloat)getHeightByWidth:(CGFloat)width font:(UIFont *)font {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 0)];
label.text = self;
label.font = font;
label.numberOfLines = 0;
[label sizeToFit];
CGFloat height = label.frame.size.height;
return ceil(height);
}
@end