我的代码:
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,这两种方法就可以工作。
不知道哪里出了问题,求大神指点,谢谢
最佳答案
正如我所看到的,您正在尝试在观察者端发布对象。恰恰相反,请参见下面的示例。
接收类
- (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];
}
关于ios - 如何使用 NSNotificationCenter 在类之间传递对象 - 传递对象失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25012459/