通知的使用
- 通知傳值
- 通知監聽
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];
}