iOS emoji messed up in UILabel

妖精的绣舞 提交于 2019-12-23 06:20:11

问题


I am using a open source UILabel subclass STTweetLabel v2.22 (Github) and trying to show emoji in the label. During my test it seems that the code can handle most cases correctly but sometimes I see this:

Just wondering why this could happen, and what could be a possible fix I should look into..

Thanks!

-- Update (adding code used to decode strings from server) --

 NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
 NSString *decoded = [[NSString alloc] initWithData:data encoding:NSNonLossyASCIIStringEncoding];

回答1:


Hi I have got one solution for that library you can find height with emoji. Please use <CoreText/CoreText.h> framework and use below code.

  - (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 +4;

}

Let me know thoughts....!!!




回答2:


Several things:

Do not use encoding:NSNonLossyASCIIStringEncoding, emoji are not ASCII. Use NSUTF8StringEncoding.

Why are you converting to NSData and then back to an NSString? That makes no sense.

There is something else going on here.



来源:https://stackoverflow.com/questions/25128643/ios-emoji-messed-up-in-uilabel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!