2013-11-01 17 views
7

我想獲取屬性字符串的高度。這是按預期工作:用emojis歸因字符串 - 適當的高度

[attrString boundingRectWithSize:size 
         options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine) 
         context:NULL] 

...除非字符串中包含表情符號。使用emojis,字符串會在標籤的底部被切掉。我需要做些什麼特別的事嗎?

+0

是你能解決這個問題?我有完全相同的問題。 – damirstuhec

回答

3

我知道這是一箇舊帖子,但有人可能仍然覺得它有用,你可以下降到核心文本,讓它爲你辛苦工作!

static inline CGSize OKASizeWithAttributedString(NSAttributedString *attributedString, CGFloat width) { 

    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attributedString); 
    CGSize targetSize = CGSizeMake(width, CGFLOAT_MAX); 
    CGSize size = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, (CFIndex)[attributedString length]), NULL, targetSize, NULL); 
    CFRelease(framesetter); 

    return size; 
} 
+0

這對我有幫助。謝謝。 – user1105951

+0

@Oliver Atkinson:我已經使用過你的code.it工作正常,但如果文本中有很多空間,那麼它將無法正常工作。 – bittu

+0

@bittu你使用什麼字體?隨着系統支持的字體,這是好的,我一般都看到使用自定義字體時出現問題 –

0
+(CGFloat)heightStringWithEmojis:(NSString*)str fontType:(UIFont *)uiFont ForWidth:(CGFloat)width { 

    // Get text 
    CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0); 
    CFAttributedStringReplaceString (attrString, CFRangeMake(0, 0), (CFStringRef) str); 
    CFIndex stringLength = CFStringGetLength((CFStringRef) attrString); 

    // Change font 
    CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef) uiFont.fontName, uiFont.pointSize, NULL); 
    CFAttributedStringSetAttribute(attrString, CFRangeMake(0, stringLength), kCTFontAttributeName, ctFont); 

    // Calc the size 
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString); 
    CFRange fitRange; 
    CGSize frameSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, 0), NULL, CGSizeMake(width, CGFLOAT_MAX), &fitRange); 

    CFRelease(ctFont); 
    CFRelease(framesetter); 
    CFRelease(attrString); 

    return frameSize.height; 

}