iOS:使用 UITextField 子类检测空 UITextField 中的退格

iOS: Detect backspace in empty UITextField with UITextField subclass

检测退格键的明确答案是创建 UITextField 的子类并覆盖 deleteBackward 属性.

我已经创建了一个 UITextField 子类的子类,但出现此错误:

'NSInvalidArgumentException', reason: '-[UITextField setMyDelegate:]: unrecognized selector sent to instance

这是我的子类代码:

我的TextField.h:

@protocol MyTextFieldDelegate <NSObject>
@optional
- (void)textFieldDidDelete;
@end

@interface MyTextField : UITextField<UIKeyInput>
//create "myDelegate"
@property (nonatomic, assign) id<MyTextFieldDelegate> myDelegate;
@end

我的TextField.m:

- (void)deleteBackward {
    [super deleteBackward];

    if ([_myDelegate respondsToSelector:@selector(textFieldDidDelete)]){
        [_myDelegate textFieldDidDelete];
    }
}

在我想访问 UITextField 子类的 ViewController 中,我执行以下操作:

 #import "MyTextField.h"

 <MyTextFieldDelegate>
 @property (nonatomic, strong) IBOutlet MyTextField *passcode1;
 self.passcode1.myDelegate = self;

关于为什么我会收到无法识别的选择器错误的任何想法?在我看来,我在子类化 UITextField 时所做的一切都是正确的。

问题出在你的插座上。 属性 是用您的自定义 class 定义的,但在 Interface Builder 中您添加了一个普通的旧 UITextField。因此在运行时出错。在 Interface Buldier 中,将文本字段的 class 更新为您的自定义 class。