UITextPosition in UITextField

futureelite7 picture futureelite7 · Mar 19, 2012 · Viewed 13.7k times · Source

Is there any way for me to get at a UITextField's current caret position through the text field's UITextRange object? Is the UITextRange returned by UITextField even of any use? The public interface for UITextPosition does not have any visible members.

Answer

Shaun McCarthy picture Shaun McCarthy · Apr 1, 2012

I was facing the same problem last night. It turns out you have to use offsetFromPosition on the UITextField to get the relative position of the "start" of the selected range to work out the position.

e.g.

// Get the selected text range
UITextRange *selectedRange = [self selectedTextRange];

//Calculate the existing position, relative to the beginning of the field
int pos = [self offsetFromPosition:self.beginningOfDocument 
                        toPosition:selectedRange.start];

I ended up using the endOfDocument as it was easier to restore the user's position after changing the text field. I wrote a blog posting on that here:

http://neofight.wordpress.com/2012/04/01/finding-the-cursor-position-in-a-uitextfield/