【问题标题】:ios textView.selectedTextRange giving wrong range for textview containing Emojisios textView.selectedTextRange 为包含 Emojis 的 textview 提供了错误的范围
【发布时间】:2018-04-23 06:06:20
【问题描述】:

我的函数想在 textview 中获取光标当前位置,但是当我在 textview 中有字符串“???? ???? ????”(光标在最后一个位置)时,它返回给我范围(0, 6)当前索引为6,预期位置为3,请告诉我是否有任何方法可以获取光标位置

func getcurserforTextView(textView : UITextView ) -> Int {

    var cursorPosition = 0

    if let selectedRange = textView.selectedTextRange {

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

【问题讨论】:

    标签: ios swift nsstring uitextview


    【解决方案1】:

    selectedRangeoffset(from:to:) 值基于文本视图中文本的 UTF-16 字符。因此,该字符串的 6 的结果是正确的,因为在使用 UTF-16 字符编码时该字符串包含 6 个字符。

    因此,根据您对获得的光标位置所做的操作,您可能需要将该 UTF-16 偏移量转换为“正常”String 索引。

    请参阅Converting scanLocation from utf16 units to character index in NSScanner (Swift),其中涵盖了类似的情况以及执行转换的方法。

    【讨论】:

    • 感谢您的回答,但我需要包含 UTF16 字符的文本视图中的光标位置,请您帮忙,当前答案仅给出总字符数
    • 你的答案在字符串和 NSString 方面是正确的,但我想要函数来获取我的课程索引,谢谢你的解释
    • 游标索引与字符串索引有何不同?请澄清。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2017-10-31
    • 2023-03-30
    • 2017-06-01
    • 2016-04-16
    • 2017-01-01
    • 2016-03-25
    相关资源
    最近更新 更多