gpt4 book ai didi

ios textView.selectedTextRange 为包含表情符号的 TextView 提供了错误的范围

转载 作者:行者123 更新时间:2023-11-28 06:09:16 47 4
gpt4 key购买 nike

我的函数想要获取光标在 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
}

最佳答案

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

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

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

关于ios textView.selectedTextRange 为包含表情符号的 TextView 提供了错误的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47215524/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com