先说NSString
方法 :
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSString *, id> *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);
举例:
NSString *testStr = @"我要用这个字符串来测试NSString的高度我要用这个字符串来测试NSString的高度我要用这个字符串来测试NSString的高度我要用这个字符串来测试NSString的高度我要用这个字符串来测试NSString的高度我要用这个字符串来测试NSString的高度我要用这个字符串来测试NSString的高度我要用这个字符串来测试NSString的高度我要用这个字符串来测试NSString的高度";
CGSize resultSize = [testStr boundingRectWithSize:CGSizeMake(375, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName : [UIFont systemFontOfSize:17] } context:nil].size;
CGFloat resultHeight = resultSize.height;
375 就是我指定的宽度 最后 resultHeight的值是182.5 就是说 testStr 这个字符串在宽度为375 字体大小为17的前提下 计算出来的高度是375
NSMutableAttributedString 富文本
方法
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 6_0);
举例
NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:str];
[attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:NSMakeRange(0, [str length])];
[self praseString:attributedString withText:str];
CGSize attSize = [attributedString boundingRectWithSize:CGSizeMake(375, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
这里 指定宽度是375 字体大小是13