0

I'm replacing the selected text in a textView with the new one. To accomplish this, I'm using this code based on this answer of beyowulf. All works well, the replaced text becomes selected, the problem arises when in the text there is one ore more special characters (like emoji etc). In this case the selected text misses one ore more characters at the end of the selection.

mainTextField.replaceRange((theRange), withText: newStr) // replace old text with the new one
selectNewText(theRange, newStr: newStr) // select the new text


func selectNewText(theRange: UITextRange, newStr: String) {
    let newStrLength = newStr.characters.count // let's see how long is the string
    mainTextField.selectedTextRange = mainTextField.textRangeFromPosition(theRange.start, toPosition: mainTextField.positionFromPosition(theRange.start, offset: newStrLength)!)
    mainTextField.becomeFirstResponder() 
}
Community
  • 1
  • 1
Cue
  • 2,952
  • 3
  • 33
  • 54

1 Answers1

0

OK, after I read the answers and comments to this question, I fixed this problem by replacing this statement (which returns the "human-perceptible" number of characters):

let newStrLength = newStr.characters.count

With this one:

let newStrLength = newStr.utf16.count

PS By the way, here is some test I done with different implementations:

let str = "Abc"

let count = str.characters.count
print(count) // 4

let count2 = str.utf16.count
print(count2) // 5

let count3 = str.utf8.count
print(count3) // 7
Community
  • 1
  • 1
Cue
  • 2,952
  • 3
  • 33
  • 54