我正在使用新文本替换textView中的选定文本。为此,我使用基于this answer of beyowulf的代码。一切正常,被替换的文本被选中,问题出现时,在文本中有一个或多个特殊字符(如表情符号等)。在这种情况下,所选文本在选择结束时错过了一个或多个字符。
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()
}
答案 0 :(得分:0)
好的,after I read the answers and comments to this question,我通过替换此语句(返回"人类可感知的"字符数)修复了此问题:
let newStrLength = newStr.characters.count
有了这个:
let newStrLength = newStr.utf16.count
PS 顺便说一下,这是我用不同的实现做的一些测试:
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