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.
UITextPosition in UITextField
14k Views Asked by futureelite7 At
2
There are 2 best solutions below
1

I used a category on uitextfield and implemented setSelectedRange and selectedRange (just like the methods implemented in the uitextview class). An example is found on B2Cloud here, with their code below:
@interface UITextField (Selection)
- (NSRange) selectedRange;
- (void) setSelectedRange:(NSRange) range;
@end
@implementation UITextField (Selection)
- (NSRange) selectedRange
{
UITextPosition* beginning = self.beginningOfDocument;
UITextRange* selectedRange = self.selectedTextRange;
UITextPosition* selectionStart = selectedRange.start;
UITextPosition* selectionEnd = selectedRange.end;
const NSInteger location = [self offsetFromPosition:beginning toPosition:selectionStart];
const NSInteger length = [self offsetFromPosition:selectionStart toPosition:selectionEnd];
return NSMakeRange(location, length);
}
- (void) setSelectedRange:(NSRange) range
{
UITextPosition* beginning = self.beginningOfDocument;
UITextPosition* startPosition = [self positionFromPosition:beginning offset:range.location];
UITextPosition* endPosition = [self positionFromPosition:beginning offset:range.location + range.length];
UITextRange* selectionRange = [self textRangeFromPosition:startPosition toPosition:endPosition];
[self setSelectedTextRange:selectionRange];
}
@end
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.
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/