iOS的文字高度计算一直是个问题, 苹果也一直在改, 这几天看了一下 boundingRectWithSize 方法.
- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options context:(NSStringDrawingContext *)context NS_AVAILABLE_IOS(6_0);
踩了几个坑后, 总算找到比较好的使用方法.
参考: http://*.com/questions/13621084/boundingrectwithsize-for-nsattributedstring-returning-wrong-size
使用时的注意事项:
1: NSAttributedString 的每个部分都要至少设置两个属性:
NSFontAttributeName
NSForegroundColorAttributeName
2: NSStringDrawingOptions 的值, 在多行的情况下, 至少要有
NSStringDrawingUsesLineFragmentOrigin
NSStringDrawingUsesFontLeading
3: 如果文字中可能会出现emoji表情的话, emoji的高度比文字要高一点点,
我的方法是简单的在高度基础上加了两个像素.
(用CoreText可能会好一些, 但相对复杂.)
附代码:
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:fullDescAndTagStr]; NSRange allRange = [fullDescAndTagStr rangeOfString:fullDescAndTagStr];
[attrStr addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:13.0]
range:allRange];
[attrStr addAttribute:NSForegroundColorAttributeName
value:[UIColor blackColor]
range:allRange]; NSRange destRange = [fullDescAndTagStr rangeOfString:tagStr];
[attrStr addAttribute:NSForegroundColorAttributeName
value:HEXCOLOR(0x009cdd)
range:destRange]; CGFloat titleHeight; NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(labelWidth, CGFLOAT_MAX)
options:options
context:nil];
titleHeight = ceilf(rect.size.height); return titleHeight+2; // 加两个像素,防止emoji被切掉.