UITextPosition in UITextField

2019-04-03 20: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.

回答1:

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/



回答2:

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