监听一个控件内部的事件

控件监听

  • 如果继承自UIControl
- (void)addTarget:(nullable id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
  • 代理

  • 通知

  • 利用内部的某些机制

    • 比如重写UITextField的becomeFirstResponderresignFirstResponder来监听UITextField的获得焦点和失去焦点事件

监听UITextField的获得焦点和失去焦点事件

  • addTarget
[textField addTarget:target action:@selector(editingDidBegin) forControlEvents:UIControlEventEditingDidBegin];
[textField addTarget:target action:@selector(editingDidEnd) forControlEvents:UIControlEventEditingDidEnd];

UIControlEventEditingDidBegin
1.开始编辑
2.获得焦点
3.弹出键盘

UIControlEventEditingDidEnd
1.结束编辑
2.失去焦点
3.退下键盘
  • delegate
textField.delegate = self;

#pragma mark - 
- (void)textFieldDidBeginEditing:(UITextField *)textField
{

}

- (void)textFieldDidEndEditing:(UITextField *)textField
{

}
  • 通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beginEditing) name:UITextFieldTextDidBeginEditingNotification object:textField];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endEditing) name:UITextFieldTextDidEndEditingNotification object:textField];

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)beginEditing
{

}

- (void)endEditing
{

}
  • 重写UITextField的becomeFirstResponderresignFirstResponder方法
/**
 *  调用时刻 : 成为第一响应者(开始编辑\弹出键盘\获得焦点)
 */
- (BOOL)becomeFirstResponder
{

    return [super becomeFirstResponder];
}

/**
 *  调用时刻 : 不做第一响应者(结束编辑\退出键盘\失去焦点)
 */
- (BOOL)resignFirstResponder
{

    return [super resignFirstResponder];
}

你可能感兴趣的:(监听一个控件内部的事件)