简体   繁体   中英

selectedTextRange always returning nil

I have a subclass of UITextField like:

@interface CustomTextField : UITextField

-(NSRange) getSelection;

@end

@implementation CustomTextField

-(NSRange) getSelection
{

    UITextRange *selectedRange = [self selectedTextRange];
    UITextPosition* selectionStart = selectedRange.start;
    UITextPosition* selectionEnd = selectedRange.end;

    const NSInteger position1 = [self offsetFromPosition:self.beginningOfDocument toPosition:selectionStart];
    const NSInteger position2 = [self offsetFromPosition:self.beginningOfDocument toPosition:selectionEnd];
    return NSMakeRange(position1, position2);
}

@end

But here whenever I place cursor in textfield, and call getSelection method selectedRange is always nil, so selectedTextRange is not updating why? when I added @synthesize selectedTextRange then the property is updated. So is there any issue with inheritance?

As mentioned in the comments, make sure your TextField is first responder. If not, call becomeFirstResponder() on the field. I had this bug on iOS 10. Starting with iOS 11 this works correctly even if your textField is not first responder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM