2

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
}
user3395433
  • 123
  • 2
  • 10

1 Answers1

2

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • thanks for answer, but i need cursor position in textview containing UTF16 character, can you please help, current answer only give total characters – user3395433 Nov 10 '17 at 09:45
  • your answer is correct in terms of string and NSString, but i want function to get me courser index, Thanks for explanation – user3395433 Nov 13 '17 at 08:04
  • How is the cursor index different from the string index? Please clarify. – rmaddy Nov 13 '17 at 14:30