Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apple Emoji / iterate through NSString

I want to iterate through the 'characters' of an Emoji input String (from a UITextField) and then, one after another, display those emoji icons with a UILabel.

for (int i=0; i < len; i++) {  
    unichar c = [transformedString characterAtIndex:i];  
    [label setText:[NSString stringWithFormat:@"%C", c]];  
...

This works for ASCII text but not Emoji fonts (all except the heart symbol are empty). As I noticed, a single Emoji icon is represented by 2 characters in the string. As far as I know, Emoji uses private area unicode chars.

Is there anyway to achieve this ?

Thank you very much, you save me some headache ...

like image 823
Patrick Avatar asked Feb 20 '23 21:02

Patrick


1 Answers

You can used one of the enumerate* instance methods on NSString, with the option NSStringEnumerationByComposedCharacterSequences.

- (void)enumerateSubstringsInRange:(NSRange)range
                           options:(NSStringEnumerationOptions)opts
                        usingBlock:(void (^)(NSString *substring,
                                             NSRange substringRange,
                                             NSRange enclosingRange,
                                             BOOL *stop))block

NSString uses UTF-16 which represents some codepoints as two 16 bit values. You could also manually check for these 'surrogate pairs' in the string and manually combine them, but then you'd still only be getting codepoints rather than characters.


[transformedString
    enumerateSubstringsInRange:NSMakeRange(0,[transformedString length]
                       options:NSStringEnumerationByComposedCharacterSequences
                    usingBlock: ^(NSString *substring,NSRange,NSRange,BOOL *)
{
    [label setText:substring];
}];
like image 76
bames53 Avatar answered Mar 04 '23 20:03

bames53