iOS开发-通知传值

2019-07-23  本文已影响0人  善良的皮蛋

通知的使用


1.通知传值 (UIViewController
NSDictionary *dict = @{@"c2cmsg":self.codeMessageValue};
[[NSNotificationCenter defaultCenter] postNotificationName:@"c2cSellout" object:nil userInfo:dict];

我碰到的情况:在scrollview上滑动创建两个类似自定义UIView导致通知重复创建,然后最终导致通知的方法被多次调用

 /** 移除特定通知-再创建不然就会重复 */
 [[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"]];
}
/** 移除通知 */
- (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];
}
上一篇 下一篇

猜你喜欢

热点阅读