UITextView: programmatically setting text to flag emoji not working.

I have a UITextView that only allows the user to input a single character, and each successive character entered overwrites the entire contents of the text view with the new character. This is done using the textView:shouldChangeTextInRange:replacementText: delegate method.


In order to deal with emoji and other unicode characters that use two 'characters' as far as NSString is concerned, I'm determining the length of the string to accept by truncating the input string to the range returned by [text rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, 1)].


This works fine for everything but the "special" emoji like flags, which are in fact made up of two unicode characters. The first issue is that I can't find a way to automatically detect if the user has entered such a character; it just appears as two separate emoji, and the above rangeOfComposedCharacterSequencesForRange call returns a range of 0,2 which encompasses only the first of them. I can make a cheap hack around this by checking if the input NSString length is exactly 4 and is composed of two characters of length 2 -- this will fail in instances where the user pastes a two-emoji string into the textview, for example, but if there's not a simple way to handle this, that's good enough for me at this point.


The second issue is that when I try to programmatically set the text of the UITextView, using myTextView.text = theTruncatedNSString, instances where theTruncatedNSString contains one of these "special" emoji, instead of displaying the flag emoji, it displays the two characters which the flag is composed of (e.g. a boxed "U" and a boxed "S" for the US flag).


How can I set the text of the UITextView programmatically so it properly displays that text?


Thanks.

An easy thing to check for would be the character's Unicode number.


Emojis should be in the range

U+1F300

to

U+27BF


Stackoverflow has some good answers for obtaining this value, and this Wikipedia article has the entire list of "special" (emoji) characters in Unicode. That way, you don't have to worry about checking ranges since the emojis can take up different lengths in NSString

UITextView: programmatically setting text to flag emoji not working.
 
 
Q