UITextPosition in UITextField
Asked Answered
G

2

16

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.

Gilbert answered 19/3, 2012 at 6:48 Comment(0)
I
20

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/

Invalidism answered 1/4, 2012 at 17:7 Comment(1)
your link point to a suspected malware site. Please check it outPulverize
S
13

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
Subtraction answered 4/12, 2012 at 13:11 Comment(1)
Thank you. Your code did help me to figure out how I can use UITextPosition with UITextView.Ensnare

© 2022 - 2024 — McMap. All rights reserved.