1、系统通知的使用方法
如下图,点击UITextField时弹出将会弹出软键盘,并会触发系统通知:
UIKeyboardWillShowNotification,本例将实现在观察到此通知时,让UITextField失去第一响应者,键盘无法弹出,具体代码如下:
、
//注册观察者,绑定监听事件,监听通知名称:UIKeyboardWillShowNotification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//当观察者(self)监听到通知(UIKeyboardWillShowNotification)时触发此方法
- (void) keyboardWillShow:(NSNotification *)notification
{
//让UITextField失去第一响应者,键盘将不会弹出
[self.txfName resignFirstResponder];
}
2、自定义通知的使用方法
如下图, 添加一个UIButton,点击button通过发送通知消息隐藏UITextField。具体代码如下:
.pch文件里定义一个通知名的宏:
#define kHiddenTxfNameNotification @"kHiddenTxfNameNotification"
viewDidLoad方法中:
//添加观察者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hiddenTxfName:) name:kHiddenTxfNameNotification object:@"string"];
//监听到kHiddenTxfNameNotification通知时触发此方法
- (void) hiddenTxfName:(NSNotification *) notification
{
NSLog(@"%@", notification.object);
if(!self.txfName.hidden)
{
self.txfName.hidden = YES;
}
}
//btnHidden点击事件,发送通知消息,观察的通知名称必须与此通知名称一致
- (IBAction)btnHiddenOnClick:(UIButton *) button
{
[[NSNotificationCenter defaultCenter] postNotificationName:kHiddenTxfNameNotification object:@"object"];
}
最后别忘了
//视图即将消失时,移除通知观察者
- (void)viewWillDisappear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:kHiddenTxfNameNotification object:nil];
}
如有错误,欢迎拍砖!