作iOS开发已经不短期了,忙于项目,碰见问题,就去Google,忘记了积累,最近深知其中的危害,深深体会到经验不在于年限而在于积累这个道理。post
从碰见的问题提及,想实现时刻监控UITextField有无文本这样一个功能,听起来很简单,感受作起来也很容易,但就是这么个简单的问题,让我花费了很长时间,非常懊恼,决定从新审视下本身,整理下这方面的知识,来提升本身!好了废话少说,进入正题!
spa
实现功能 监控UITextField是否有输入文本 从而实现按钮是否能够点击
code
解决方案 Notificationorm
代码实现server
//文本框 UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 100, 280, 50)]; textField.tag = 888; [textField setClearButtonMode:UITextFieldViewModeWhileEditing]; [textField setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter]; textField.layer.borderWidth = 0.5f; //添加文本改变通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextFieldTextDidChangeNotification object:textField]; [self.view addSubview:textField]; //文本框内容改变时触发 - (void) textChanged:(NSNotification *) notification { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"%@",notification.object] delegate:nil cancelButtonTitle:@"肯定" otherButtonTitles:nil]; [alertView show]; }
由此引起的一些思考,想详细整理下 KVO 和 Notification 的使用对象
KVO开发
1.什么是KVOrem
KVO 即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。编译器
简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。string
2.实现步骤:
1)注册(指定被观察者的属性)
2)实现回调方法
3)移除观察
3.代码实现
//文本框 UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 100, 280, 50)]; textField.tag = 888; [textField setClearButtonMode:UITextFieldViewModeWhileEditing]; [textField setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter]; //1.注册 [textField addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; textField.layer.borderWidth = 0.5f; [self.view addSubview:textField]; //2.实现回调方法 - (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"text"]) { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"%@",object] delegate:nil cancelButtonTitle:@"肯定" otherButtonTitles:nil]; [alertView show]; } } //3.移除通知 UITextField *textField = (UITextField *)[self.view viewWithTag:888]; [textField removeObserver:self forKeyPath:@"text"];
Notification
做用: NSNotificationCenter是专门供程序中不一样类间的消息通讯而设置的.
2.实现步骤:
1)注册(在什么地方接收消息)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test:) name:@"TestNotification" object:nil];
2)发送通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:myObject];
注:postNotificationName:通知的名字,也是通知的惟一标示,编译器就经过这个找到通知。
object:传递的参数
3)注册方法的写法:
- (void) test:(NSNotification*) notification
{
id obj = [notification object];//获取到传递的参数 即上方的myObject
}
4)移除通知
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"TestNotification" object:nil];