views:

2583

answers:

3

Hi all

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?

Thanks

-Alex

+2  A: 

Have you tried UITextView.selectedRange? It returns an NSRange whose location element should tell you where the cursor is.

drewh
+5  A: 

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];
jpedroso
Note that with iPhone 3.0, it is no longer true that the length of the range is always zero. If the user has text selected, then the length will be non-zero. In this case, you may want to use replaceCharactersInRange:withString: instead of insertString::atIndex:. You should also set the new selection range appropriately.
Kristopher Johnson
+3  A: 

Use UITextView selectedRange property to find the insertion point when the text view is first responder. Otherwise, when the view is not in focus, this property returns NSNotFound. If you need to know the cursor position in that case, consider subclassing UITextView and overriding canResignFirstResponder method, where you can store cursor position to a member variable.

Vladimir Grigorov
This is great info that is easy to miss. I can't tell you how long it took my to figure out why the selectedRange.location was returning NSNotFound. You can check for invalid location with:if (myTextField.selectedRange.location == NSNotFound)
Harkonian