UITextField 添加点击事件

需求

点击 UITextField 没有成为第一响应者,而是触发一个事件。

常规做法 UITapGestureRecognizer

1
2
3
4
5
6
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
[self.searchTextField addGestureRecognizer:tap];

- (void)tapGesture:(UIGestureRecognizer *)gesture {
NSLog(@"--%@", gesture);
}

这样做可以触发一个事件,同时也成为了第一响应者。那么怎样不让 UITextField 成为第一响应者呢?可以通过委托事件完成

1
2
3
4
5
self.searchTextField.delegate = self;

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
return NO;
}

正确的做法

其实并不需要添加手势事件,直接在委托方法中就可以处理想要的逻辑。

1
2
3
4
5
6
self.searchTextField.delegate = self;

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
// 在这里处理需要的逻辑
return NO;
}

扩展

这种做法同样适应于 UITextView 。