UITextView.text 表情符号设置:cursorPosition 不正确
UITextView.text with emoji setting: cursorPosition is not correct
此处str
包含表情符号且设置的cursorPosition不正确:
let cursorPosition = str.characters.count
let cursorRange = NSRange(location: cursorPosition, length: 0)
textInputView.selectedRange = cursorRange
textInputView.scrollRangeToVisible(cursorRange)
看起来您想将光标放在 textView
的最后。这样试试
textInputView.becomeFirstResponder()
let cursorPosition = str.utf16.count
let cursorRange = NSRange(location: cursorPosition, length: 0)
textInputView.selectedRange = cursorRange
textInputView.scrollRangeToVisible(cursorRange)
这是一个老问题,但如果我再次运行解决这个问题,我会补充一些要点:
Nirav D 如果您只想转到字符串的末尾,则答案有效。
发生这种情况是因为虽然表情符号算作字符串中的单个字符位置,但它们在文本字段中算作多个位置,因为光标位置使用 utf16 字符串位置。这就是为什么光标不会通过您的代码到达文本字段的末尾。
如果要将光标移动到末尾以外的任意点,使用string.utf16对应的位置。
此处str
包含表情符号且设置的cursorPosition不正确:
let cursorPosition = str.characters.count
let cursorRange = NSRange(location: cursorPosition, length: 0)
textInputView.selectedRange = cursorRange
textInputView.scrollRangeToVisible(cursorRange)
看起来您想将光标放在 textView
的最后。这样试试
textInputView.becomeFirstResponder()
let cursorPosition = str.utf16.count
let cursorRange = NSRange(location: cursorPosition, length: 0)
textInputView.selectedRange = cursorRange
textInputView.scrollRangeToVisible(cursorRange)
这是一个老问题,但如果我再次运行解决这个问题,我会补充一些要点:
Nirav D 如果您只想转到字符串的末尾,则答案有效。
发生这种情况是因为虽然表情符号算作字符串中的单个字符位置,但它们在文本字段中算作多个位置,因为光标位置使用 utf16 字符串位置。这就是为什么光标不会通过您的代码到达文本字段的末尾。
如果要将光标移动到末尾以外的任意点,使用string.utf16对应的位置。