Ios UIKeyboardWillShowNotification

Ios UIKeyboardWillShowNotification,ios,objective-c,Ios,Objective C,我有一个观察者观察UIKeyboardWillShowNotification和UIKeyboardWillHideNotification [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter]

我有一个观察者观察
UIKeyboardWillShowNotification
UIKeyboardWillHideNotification

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
除了viewController当前不可见时,它都可以工作


我尝试过与self.navigationcontroller.topViewController进行比较,但是当我有一个模式视图时,这不起作用,因为
topViewController
是模式视图控制器下面的一个。如果您只想在viewController可见时对该通知作出反应,然后只需检查在函数开头是否可见:

- (void)keyboardWillShow:(NSNotification *)notification
{
    if ([self.view window]) //means is visible
        //do something
    else 
        //return
}

如果您使用的是
UIViewController
,当视图在
视图中可见时,您可以注册键盘通知实例:
,然后当视图在
视图中隐藏时取消注册:
这样,当视图不可见时,您将不会收到通知


希望这有帮助

如果视图控制器不可见,为什么要观察事件?嗯。。。我想我可以在视图中添加侦听器,并在视图中删除侦听器。当您呈现模态视图控制器时,是否调用ViewWillEnglish?是。通常情况下,您只需要根据需要运行观察者。谢谢。如果您想回答,我将接受+1,因为我不知道
[self.view window]
功能。但使用了不同的解决方案。ThanksGreat也是如此,这是一个很好的约定,在不需要时删除观察者。使用
self.view
会产生副作用,即如果尚未加载视图,则会加载该视图。你应该先检查
isviewsloaded
。这是真的,但是他正在检查一个已经可见的视图,所以不可能不加载。当俯视图是模态视图时,答案不起作用。因为不会调用父视图的ViewWillEnglish。