UITextField — observe changes to selectedTextRange

2019-07-14 07:00发布

问题:

Is there any way to observe changes to the selectedTextRange of a UITextField?

I tried observing all UIControlEvents. But changing the selectedTextRange does not trigger a UIControlEvent.

Another dead end -- UIKit classes are not KVO compliant.

Then there is the UITextFieldTextDidChangeNotification. But that's for changes to the text.

Any ideas?

回答1:

Subclass UITextField as follows.

@interface WJTextField : UITextField
@end

@protocol WJTextFieldDelegate <UITextFieldDelegate>
- (void) textFieldDidChangeSelection: (UITextField *) textField;
@end

Implementation:

@implementation WJTextField

- (void) setSelectedTextRange: (UITextRange *) selectedTextRange
{
    [super setSelectedTextRange: selectedTextRange];
    if ([self.delegate respondsToSelector: @selector(textFieldDidChangeSelection:)])
        [(id <WJTextFieldDelegate>) self.delegate textFieldDidChangeSelection: self];
}

@end

Then add -textFieldDidChangeSelection: to your text field's delegate.

Caveat: This delegate message will be sent only when the cursor is moved, it will not be sent when typing or pasting text, for those events you have to implement textField:shouldChangeCharactersInRange:replacementString:, where the selection range is going to either be set to range.location + [string length] (if you return YES) or remain the same (if you return NO).