I am trying to implement my own keyboard containing emojis.
For this purpose I am inserting the emoji in the cursor position.
This works fine if no 4-bytes emoji characters exist in UITextField. Otherwise the app gets crashed.
I am posting the insertion code here. Can someone point out how to solve the issue?
UITextField *field = self.textField;
UITextRange *range = field.selectedTextRange;
int pos = [field offsetFromPosition:field.beginningOfDocument toPosition:range.end];
NSString * firstHalfString = [field.text substringToIndex:pos];
NSString * secondHalfString = [field.text substringFromIndex:pos];
field.text = [NSString stringWithFormat: @"%@%@%@", firstHalfString, emoticon, secondHalfString];
UITextPosition *newPos = [field positionFromPosition:field.beginningOfDocument offset:pos + 1];
field.selectedTextRange = [field textRangeFromPosition:newPos toPosition:newPos];
this line returns nil if there are emojis in the text:
UITextPosition *newPos = [field positionFromPosition:field.beginningOfDocument offset:pos + 1];
At the end I solved this by writing my own length and offset calculation methods which count 4-byte characters as 1 character, not two.
see the full blog post http://bit.ly/PT9VSz