这里我用UITextField作演示,监听一个类时首先考虑的是自定义它,然后整体监听它。
一、addTarget。(凡是继承于UIControl都可以使用addTarget)
//添加监听
[self addTarget:self action:@selector(startEdit) forControlEvents:UIControlEventEditingDidBegin];
[self addTarget:self action:@selector(endEdit) forControlEvents:UIControlEventEditingDidEnd];
//实现监听
- (void)startEdit{
NSLog(@"%s",__func__);
self.placeholderColor = [UIColor redColor];
}
- (void)endEdit{
NSLog(@"%s",__func__);
self.placeholderColor = [UIColor grayColor];
}
//个人感觉比通知简单点
二、通知
//开始编辑
[[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(startEdit:) name:UITextFieldTextDidBeginEditingNotification object:self];
//完成编辑
[[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(endEdit:) name:UITextFieldTextDidEndEditingNotification object:self];
//实现监听的方法
- (void)startEdit:(NSNotification *)noti{
NSLog(@"%s",__func__);
self.placeholderColor = [UIColor redColor]; //这里的placeholderColor是自定义封装的属性,目的是设置占位符的颜色
}
- (void)endEdit:(NSNotification *)noti{
NSLog(@"%s",__func__);
self.placeholderColor = [UIColor grayColor];
}
//删除通知
- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
三、代理
//使用代理在这里有个弊端,当外面再设置为这个textField为代理时,会不起作用,或者是这里代码不再起作用
,珍惜生命,谨慎使用。
self.delegate = self;
//实现代理的方法
#pragma mark ---UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
return YES; //是否允许编辑
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
//开始编辑
self.placeholderColor = [UIColor redColor];
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
//是否结束允许编辑
return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
self.placeholderColor = nil;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
return YES; //是否可以改变文字
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{
//是否可以清除
return NO;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
//是否可以返回
return YES;
四、系统的一些方法
//如果你完全了解一个控件,完全可以使用这个方法,好简单有木有
- (BOOL)becomeFirstResponder{
self.placeholderColor = [UIColor whiteColor]; //当得到焦点时设置成白色
return [super becomeFirstResponder]; //这里让系统父类正常返回
}
- (BOOL)resignFirstResponder{
self.placeholderColor = nil;
return [super resignFirstResponder];
}