UITextField中的UITextPosition

fut*_*te7 16 uitextfield ios uitextrange uitextposition

有没有办法通过文本字段的UITextRange对象获取UITextField当前的插入位置?即使有任何用途,UITextField还是返回了UITextRange吗?UITextPosition的公共接口没有任何可见成员.

Sha*_*thy 20

我昨晚遇到了同样的问题.事实证明,你必须在UITextField上使用offsetFromPosition来获得所选范围的"开始"的相对位置以计算出位置.

例如

// 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];
Run Code Online (Sandbox Code Playgroud)

我最终使用了endOfDocument,因为在更改文本字段后更容易恢复用户的位置.我在这里写了一篇博文:

http://neofight.wordpress.com/2012/04/01/finding-the-cursor-position-in-a-uitextfield/


Jbr*_*son 13

我在uitextfield上使用了一个类,并实现了setSelectedRange和selectedRange(就像在uitextview类中实现的方法一样).这里有一个关于B2Cloud的例子,它们的代码如下:

@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
Run Code Online (Sandbox Code Playgroud)