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.


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.


// 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 

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:


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;

@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];


Need Your Help

.NET Signalr MapConnection is Obsolete?

asp.net .net signalr

I am new to .Net and SignalR. I am looking at some code written by a former coworker and he added this line to the Route Config which is now throwing errors saying its obsolete but all the documen...

#1071 - Specified key was too long; max key length is 1000 bytes

mysql phpmyadmin mysqldump

I know questions with this title have been answered before, but please do read on. I've read thoroughly all the other questions/answers on this error before posting.