selectedTextRange always returning nil

581 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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.