UITextField ― observe changes to selectedTextRange?

匿名 (未验证) 提交于 2019-12-03 01:00:01

问题:

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).



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