Skip to content

Instantly share code, notes, and snippets.

@rakkang
Last active May 12, 2016 07:44
Show Gist options
  • Save rakkang/555479ec48d6a424b99d to your computer and use it in GitHub Desktop.
Save rakkang/555479ec48d6a424b99d to your computer and use it in GitHub Desktop.
UILabel计算文本高度
// 方法一:
/*
1: NSAttributedString 的每个部分都要至少设置两个属性:
NSFontAttributeName
NSForegroundColorAttributeName
2: NSStringDrawingOptions 的值, 在多行的情况下, 至少要有
NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
3: 如果文字中可能会出现emoji表情的话, emoji的高度比文字要高一点点,
*/
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被切掉.
// 方法二:
UITextView *view = [[UITextView alloc] initWithFrame:collectionView.frame];
view.text = _postItem.content;
view.font = [UIFont systemFontOfSize:17.0];
CGSize size = [view sizeThatFits:CGSizeMake(CGRectGetWidth(collectionView.frame), CGFLOAT_MAX)];
view = nil;
// 方法三:
- (CGSize)frameSizeForAttributedString:(NSAttributedString *)attributedString
{
CTTypesetterRef typesetter = CTTypesetterCreateWithAttributedString((CFAttributedStringRef)attributedString);
CGFloat width = YOUR_FIXED_WIDTH;
CFIndex offset = 0, length;
CGFloat y = 0;
do {
length = CTTypesetterSuggestLineBreak(typesetter, offset, width);
CTLineRef line = CTTypesetterCreateLine(typesetter, CFRangeMake(offset, length));
CGFloat ascent, descent, leading;
CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
CFRelease(line);
offset += length;
y += ascent + descent + leading;
} while (offset < [attributedString length]);
CFRelease(typesetter);
return CGSizeMake(width, ceil(y));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment