我的代码:
NSDictionary *dict = @{@"1": @"_infoView3",
@"2": [NSNumber numberWithFloat:_showSelectionView.frame.size.height]
};
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:@"UIKeyboardWillShowNotification"
object:dict];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidHide:)
name:@"UIKeyboardDidHideNotification"
object:dict];
和:
- (void) keyboardWillShow:(NSNotification *)note {
NSDictionary *userInfo = [note userInfo];
CGSize kbSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
// move the view up by 30 pts
CGRect frame = self.view.frame;
frame.origin.y = -kbSize.height;
[UIView animateWithDuration:0.3 animations:^{
self.view.frame = frame;
}];
}
- (void) keyboardDidHide:(NSNotification *)note {
// move the view back to the origin
CGRect frame = self.view.frame;
frame.origin.y = 0;
[UIView animateWithDuration:0.3 animations:^{
self.view.frame = frame;
}];
}
但是当键盘显示或隐藏时,这两种方法无效。 如果我传递对象nil而不是dict,那么这两种方法都有效。
我不知道问题出在哪里,请帮助我,谢谢。
答案 0 :(得分:15)
我可以看到你试图在观察者一侧发布对象。这是完全相反的,见下面的例子。
接收者类
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveNotification:)
name:@"myNotification"
object:nil];
}
- (void)receiveNotification:(NSNotification *)notification
{
if ([[notification name] isEqualToString:@"myNotification"]) {
NSDictionary *myDictionary = (NSDictionary *)notification.object;
//doSomething here.
}
}
发件人类
- (void)sendNotification {
[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" object:YOUR_DICTIONARY];
}
答案 1 :(得分:2)
那是因为object
参数用于指定要观察的特定对象,而不是用于将任意数据传递给被调用的选择器。
来自reference:
notificationSender
观察者想要通知的对象 受到;也就是说,只有此发件人发送的通知才是 交付给观察员。
如果您通过
nil
,则通知中心不会使用通知 发送者决定是否将其传递给观察者。