以监听UITextField的获得焦点和失去焦点事件
方法一
如果继承自UIControl
- (void)addTarget:(nullable id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
方法二
代理方法
监听UITextField的获得焦点和失去焦点事件
textField.delegate = self;
[textField addTarget:target action:@selector(editingDidBegin) forControlEvents:UIControlEventEditingDidBegin];
[textField addTarget:target action:@selector(editingDidEnd) forControlEvents:UIControlEventEditingDidEnd];
UIControlEventEditingDidBegin 1.开始编辑 2.获得焦点 3.弹出键盘
UIControlEventEditingDidEnd 1.结束编辑 2.失去焦点 3.退下键盘
// 代理方法
#pragma mark -
// 是否开始编辑
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
}
//是否结束编辑
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
}
// 开始编辑
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
}
// 结束编辑
- (void)textFieldDidEndEditing:(UITextField *)textField
{
}
方法三
通知1
NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
[notification addObserver:self selector:@selector(beginEditing) name:UITextFieldTextDidBeginEditingNotification object:self];
[notification addObserver:self selector:@selector(endEditing) name:UITextFieldTextDidEndEditingNotification object:self];
// 释放监听
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)beginEditing
{
}
- (void)endEditing
{
}
通知2 使用block监听通知
NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
// object对象发出了名字为name的通知, 就在queue队列中执行block
self.observer = [notification addObserverForName:UITextFieldTextDidBeginEditingNotification object:self queue:[[NSOperationQueue alloc] init] usingBlock:^(NSNotification * _Nonnull note) {
// 一旦监听到通知, 就会执行这个block中的代码
}];
// 最后需要移除监听
[[NSNotificationCenter defaultCenter] removeObserver:self.observer];
一次性通知(监听1次后就不再监听)
id observer = [[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidBeginEditingNotification object:self queue:[[NSOperationQueue alloc] init] usingBlock:^(NSNotification * _Nonnull note) {
// 移除通知
[[NSNotificationCenter defaultCenter] removeObserver:observer];
}];
在子线程注册了通知
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// 因为是在子线程注册了通知监听器, 所以beginEditing和endEditing会在子线程中执行
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beginEditing) name:UITextFieldTextDidBeginEditingNotification object:self];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endEditing) name:UITextFieldTextDidEndEditingNotification object:self];
});
方法四
利用内部的某些机制
重写UITextField的becomeFirstResponder和resignFirstResponder方法
//调用时刻 : 成为第一响应者(开始编辑\弹出键盘\获得焦点)
- (BOOL)becomeFirstResponder
{
return [super becomeFirstResponder];
}
// 调用时刻 : 不做第一响应者(结束编辑\退出键盘\失去焦点)
- (BOOL)resignFirstResponder
{
return [super resignFirstResponder];
}