Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cursor position in a UITextView

I am looking for a non private way to find the position of the Cursor or Caret (blinking bar) in a UITextView preferably as a CGPoint.

There may be a question like this already but it does not provide a definitive way for doing it. And, I do not mean the NSRange of the selected area.

like image 696
Joshua Avatar asked Sep 09 '10 17:09

Joshua


People also ask

How do I change the cursor position in textarea?

To set the cursor at the end of a textarea: Use the setSelectionRange() method to set the current text selection position to the end of the textarea. Call the focus() method on the textarea element. The focus method will move the cursor to the end of the element's value.


2 Answers

Just got it in another thread:

Requires iOS 3.2 or later.

CGPoint cursorPosition = [textview caretRectForPosition:textview.selectedTextRange.start].origin;

Remember to check that selectedTextRange is not nil before calling this method. You should also use selectedTextRange.empty to check that it is the cursor position and not the beginning of a text range. So:

if (textview.selectedTextRange.empty) {
// get cursor position and do stuff ...
}

Pixel-Position of Cursor in UITextView

like image 85
civic.LiLister Avatar answered Oct 18 '22 22:10

civic.LiLister


SWIFT 2.1 version:

let cursorPosition = infoTextView.caretRectForPosition( (infoTextView.selectedTextRange?.start)! ).origin

print("cursorPosition:\(cursorPosition)")
like image 38
Trevor Avatar answered Oct 18 '22 22:10

Trevor