通知的使用
- 通知传值
- 通知监听
1.通知传值 (UIViewController
)
NSDictionary *dict = @{@"c2cmsg":self.codeMessageValue};
[[NSNotificationCenter defaultCenter] postNotificationName:@"c2cSellout" object:nil userInfo:dict];
我碰到的情况:在
scrollview
上滑动创建两个类似自定义UIView
导致通知重复创建,然后最终导致通知的方法被多次调用
- 首先在刷新自定义UIView的时候先移除一次通知(
CustomView
)
/** 移除特定通知-再创建不然就会重复 */
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"c2cSellout" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sellc2cout:) name:@"c2cSellout" object:nil];
#pragma mark - 监听
- (void)sellc2cout:(NSNotification *)notification{
/** 移除特定通知-再创建不然就会重复 */
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"c2cSellout" object:nil];
[self loadPublishOrderWithType:MYDC2CTransCenterViewTypeForSell valicode:notification.userInfo[@"c2cmsg"]];
}
- 移除通知(UIViewcontroller CustomView)
/** 移除通知 */
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
2.通知监听
/** 注册监听通知-键盘回收和展开 */
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardWillHideNotification object:nil];
- 监听键盘弹出
- (void)keyboardWillChangeFrame:(NSNotification *)notification{
//取出键盘动画的时间(根据userInfo的key----UIKeyboardAnimationDurationUserInfoKey)
CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
//取得键盘最后的frame(根据userInfo的key----UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 227}, {320, 253}}";)
CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//计算控制器的view需要平移的距离
CGFloat transformY = keyboardFrame.origin.y - self.view.frame.size.height;
//执行动画
[UIView animateWithDuration:duration animations:^{
[self.codeContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
make.left.right.equalTo(self.codeBgView);
make.height.equalTo(@(SCREEN_HEIGHT*0.4));
make.bottom.equalTo(self.codeBgView.mas_bottom).offset(transformY-90);
}];
}];
}
- 监听键盘收回
- (void)keyboardDidHide:(NSNotification *)notification{
CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
[UIView animateWithDuration:duration animations:^{
[self.codeContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
make.left.right.bottom.equalTo(self.codeBgView);
make.height.equalTo(@(SCREEN_HEIGHT*0.4));
}];
}];
}
- 最后移除通知
/** 移除通知 */
- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
网友评论