Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting cursor position in a UITextView on the iPhone?

We have a UITextView in our iPhone app which is editable. We need to insert some text at the cursor location when the users presses some toolbar buttons but can't seem to find a documented (or undocumented) method of finding the current location of the cursor.

Does anybody have any ideas or has anybody else achieved anything similar?

like image 827
user74686 Avatar asked Mar 06 '09 12:03

user74686


2 Answers

Like drewh said, you can use UITextView's selectedRange to return the insertion point. The length of this range is always zero. The example below shows how to it.

NSString *contentsToAdd = @"some string";
NSRange cursorPosition = [tf selectedRange];
NSMutableString *tfContent = [[NSMutableString alloc] initWithString:[tf text]];
[tfContent insertString:contentsToAdd atIndex:cursorPosition.location];
[theTextField setText:tfContent];
[tfContent release];
like image 62
jpedroso Avatar answered Oct 23 '22 11:10

jpedroso


Swift 4:

// lets be safe, thus if-let
if let cursorPosition = textView.selectedTextRange?.start {
    // cursorPosition is a UITextPosition object describing position in the text

    // if you want to know its position in textView in points:
    let caretPositionRect = textView.caretRect(for: cursorPosition)
}

We simply use textView.selectedTextRange to get selected text range and cursor position is at its start position.

like image 13
Milan Nosáľ Avatar answered Oct 23 '22 13:10

Milan Nosáľ