UITextPosition in UITextField

北战南征 提交于 2019-12-04 00:51:53

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/

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!