Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextPosition in UITextField

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.

like image 266
futureelite7 Avatar asked Mar 19 '12 06:03

futureelite7


1 Answers

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/

like image 79
Shaun McCarthy Avatar answered Oct 19 '22 11:10

Shaun McCarthy