检测包含表情符号的 UITextView 中的光标位置 returns swift 中的错误位置 4

Detecting Cursor position in UITextView that contains emojis returns the wrong position in swift 4

我正在使用此代码检测光标在 UITextView 中的位置:

if let selectedRange = textView.selectedTextRange {

    let cursorPosition = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)

    print("\(cursorPosition)")
}

我把它放在 textViewDidChange 函数下,用于在每次文本更改时检测光标位置。 它工作正常,但是当我放置表情符号时,textView.text.count 光标位置 不同。来自swift 4 每个表情符号算作一个字符,但似乎光标位置不同。

所以我怎样才能得到与文本中字符数相匹配的准确光标位置?

长话短说:将 Swift 与 StringNSRange 一起使用时,请使用此扩展名进行范围转换

extension String {
    /// Fixes the problem with `NSRange` to `Range` conversion
    var range: NSRange {
        let fromIndex = unicodeScalars.index(unicodeScalars.startIndex, offsetBy: 0)
        let toIndex = unicodeScalars.index(fromIndex, offsetBy: count)
        return NSRange(fromIndex..<toIndex, in: self)
    }
}

让我们深入了解一下:

let myStr = "Wéll helló ⚙️"
myStr.count // 12
myStr.unicodeScalars.count // 13
myStr.utf8.count // 19
myStr.utf16.count // 13

Swift 4字符串是一组字符(复合字符如ö和emoji将算作一个字符). UTF-8UTF-16视图分别是UTF-8和UTF-16编码单元的集合。

你的问题是,textView.text.count 计算集合元素(表情符号和复合字符将算作一个元素)并且 NSRange 计算索引UTF-16 代码单元。上面的片段说明了差异。


更多信息在这里: Strings And Characters