Faced a problem when, due to the use of emoji, the cursor position shifts by one position. For example, if you write "text", then if the cursor is at the end of a word, then its position will be 5, but if you immediately put a smiley after this word, then the cursor behind the smiley will already have position 7, although the logic would be 6.

I understand that this is due to the fact that more bits are used for emoji and because of this, the position is shifted. But how then to find out the real position of the cursor?

If you work with simple text, then I just subtracted 1 from the position of the cursor and received the index of the character after which the cursor stands (well, except for the case when the cursor is at the very beginning of the text and its position is 0). But if you use emoji, this technique does not work.

    1 answer 1

    I have been digging for a long time and found a solution. A small function that converts the original cursor position into an analogue of the index (as is the case with the cursor position with ordinary single-bit characters).

    func getRealCurPosition (text text: String, cur: Int) -> Int { if text != "" { var byteSumm = 0 var i = 0 for char in text.characters { byteSumm += String(char).utf16.count i += 1 if byteSumm == cur { return i } } } return 0 } 

    The principle is simple - a counter is created to add the sums of bits of each character. Pass through the array of characters of the string and find the size in the 16-bit mode of each character of the string and add this size to the total bit counter. When the bit counter coincides with the position of the cursor the index number of this symbol will be the symbol number after which the cursor is located.