Reputation: 123
My function wants to get cursor current position in textview, but when i have string "😳 😱 😨 " (cursor is at last position)in textview and it return me range (0,6) and current index as 6, expected position is 3,Please let me know if any way to get cursor position
func getcurserforTextView(textView : UITextView ) -> Int {
var cursorPosition = 0
if let selectedRange = textView.selectedTextRange {
cursorPosition = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
}
return cursorPosition
}
Upvotes: 2
Views: 1386
Reputation: 318874
The selectedRange
and offset(from:to:)
values are based on the UTF-16 characters for the text in the text view. So the result of 6 for that string is correct since that string contains 6 characters when using the UTF-16 character encoding.
So depending on what you are doing with the obtained cursor position, you may need to convert that UTF-16 offset to a "normal" String
index.
Please see Converting scanLocation from utf16 units to character index in NSScanner (Swift) which covers a similar situation and a way to perform the conversion.
Upvotes: 2