美文网首页
通知使用方法

通知使用方法

作者: jeasonDong | 来源:发表于2017-03-18 12:17 被阅读0次

通知的使用方式

1.注册通知 实现通知方法

#pragma mark --拿到通知对象

   NSNotificationCenter *noti = [NSNotificationCenter defaultCenter];

#pragma mark --注册通知

   //注册通知

   [noti addObserver:self selector:@selector(loadTableViewDataWithFooterView:) name:@"addData" object:nil];

#pragma mark -- 实现通知的方法

- (void)loadTableViewDataWithFooterView:(NSNotification *)noti {

    NSLog(@“方法实现了”);

}

#pragma mark -- 调用dealloc销毁通知 (必须实现) 否则会不断的发送通知,非常影响程序的性能

- (void)dealloc {

   [[NSNotificationCenter defaultCenter] removeObserver:self];

}

2.发送通知

#pragma mark -- 拿到通知对象

   NSNotificationCenter *noti = [NSNotificationCenter defaultCenter];

#pragma mark -- 根据通知名称发送通知实现通知方法

   // name :通知名称

   // object: 通知的发布者

   //userInfo: 额外信息

   [noti postNotificationName:@"addData" object:nil userInfo:@{@"footerView" : self}];

}

通知一般在调用系统键盘的时候使用

或者在两个控制器之间需要监听事件的时候使用

还有是在控件有多层子控制器嵌套的孙子控件需要跟最外层的控件需要相互响应事件的时候调用

//使用通知监听键盘的弹出和缩回

// 4.获取通知中心平台

   NSNotificationCenter *noti = [NSNotificationCenter defaultCenter];

   // 5.注册通知监听

   [noti addObserver:self selector:@selector(keyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];

#pragma mark - 收到UIKeyboardWillChangeFrameNotification的通知就会调用此方法

- (void)keyboardWillChangeFrameNotification:(NSNotification *)noti {

   NSDictionary *keyboardDict = noti.userInfo;

   NSLog(@"%@", keyboardDict);

   // 获取键盘变化后的frame

  CGRect keyboardFrame = [keyboardDict[UIKeyboardFrameEndUserInfoKey] CGRectValue];

   // 用键盘的Y - 屏幕的高

   //    451 - 603 - 64= -216

   // 667 - 603 - 64 = 0

   // 计算控制器view上下要移动的距离

#warning mark - 嵌入导航控制器之后一定要注册控制器view的高度问题

   CGFloat transformY = keyboardFrame.origin.y - self.view.bounds.size.height - 64;

   NSLog(@"\n\n%.f  ---%.f", transformY, self.view.bounds.size.height);

   // 让控制器view移动的时间和键盘弹出动画时间一样

   [UIView animateWithDuration:0.25 animations:^{

       self.view.transform = CGAffineTransformMakeTranslation(0, transformY);

   }];

}

#pragma mark - 对象销毁时把它从通知中心移除

- (void)dealloc {

   [[NSNotificationCenter defaultCenter] removeObserver:self];

}

相关文章

网友评论

      本文标题:通知使用方法

      本文链接:https://www.haomeiwen.com/subject/hquunttx.html