- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options context:(NSStringDrawingContext *)context NS_AVAILABLE_IOS(6_0);
使用時的注意事項:spa
1: NSAttributedString 的每一個部分都要至少設置兩個屬性: code
NSFontAttributeNameorm
NSForegroundColorAttributeNameit
2: NSStringDrawingOptions 的值, 在多行的狀況下, 至少要有 io
NSStringDrawingUsesLineFragmentOrigintable
NSStringDrawingUsesFontLeadingclass
3: 若是文字中可能會出現emoji表情的話, emoji的高度比文字要高一點點, 基礎
個人方即是簡單的在高度基礎上加了兩個像素. emoji
(用CoreText可能會好一些, 但相對複雜.)im
4.
labels.numberOfLines = 0; 行數可變
附代碼:
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被切掉.