Alex Rivera | Logout

Getting cursor position in a UITextView on the iPhone?

Asked 2009-03-06T12:51:43.783
31

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?

Edit
Report

1 Answer

31

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];
answered 2009-03-06T15:14:09.213

Your Answer