测试发现iOS7.0里计算带emoji字符串高度时会不正确,而早于7.0版或7.1以上版本都没有这个问题。有使用生成一个label,然后返回label.frame.size.height,但测试发现太耗费性能了。所以写了以下这种方法测试可以
+ (CGFloat)heightWithText:(NSString *)text font:(UIFont *)font constrainedToWidth:(CGFloat)width
{
// 早于7.0或7.1以上 Christ
if (kSystemVersionPriorToIOS7||kSystemVersionReachesIOS71) {
CGSize strSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(width,CGFLOAT_MAX)];
return ceilf(strSize.height);
}
// iOS7.0版本 Christ
else
{
// Get text
CFMutableAttributedStringRef attrString =CFAttributedStringCreateMutable(kCFAllocatorDefault,0);
CFAttributedStringReplaceString (attrString,CFRangeMake(0,0), (CFStringRef) text);
CFIndex stringLength = CFStringGetLength((CFStringRef) attrString);
// Change font
CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef) font.fontName, font.pointSize,NULL);
CFAttributedStringSetAttribute(attrString, CFRangeMake(0, stringLength), kCTFontAttributeName, ctFont);
// Calc the size
CTFramesetterRef framesetter =CTFramesetterCreateWithAttributedString(attrString);
CFRange fitRange;
CGSize frameSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, stringLength), NULL, CGSizeMake(width, CGFLOAT_MAX), &fitRange);
CFRelease(ctFont);
CFRelease(framesetter);
CFRelease(attrString);
return frameSize.height;
}
}