Question

I have one view controller (UICollectionView) that contains textfields. In this controller I listen for UIKeyboardDidShowNotification:s. Like this:

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardDidShow:)
                                             name:UIKeyboardDidShowNotification  object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillBeHidden:)
                                             name:UIKeyboardWillHideNotification object:nil];
}

And in viewWillAppear:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self registerForKeyboardNotifications];
    [...]

In another view controller I have a UITextView. This controller also listens for UIKeyboardDidShowNotification. Before I push this second view controller I remove the first view controller as an observer:

- (void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

But when the keyboard appears in VC2, then the keyboardDidShow actions also gets called in VC1, causing unwanted animations. Is it possible to avoid this behaviour somehow?

Update The strange thing is that the notification actions in VC1 gets called when I tap the back button in VC2.

Was it helpful?

Solution

Before I push this second view controller I remove the first view controller as an observer:

Maybe that is not what is happening. In fact, it seems to me that it is impossible that viewWillDisappear comes before pushing.

I am not sure but when you push a new view controller and the keyboard comes up right away, maybe the notification is fired before the other view did disappear.

You could try removing the observer when you initiated the push (e.g. in prepareForSegue).

OTHER TIPS

I guess that in VC2 you show the keyboard in loadView or viewDidLoad, so the order is: VC2 viewDidLoad,keyboardShow,VC1 viewWillDisappear。

So in keyboardDidShow method, you can do something only when the visibleController is self.

In addition, I don't think you should handle this notification in viewWillDisappear or viewWillDisappear, try a better way. And you must removeObserver in dealloc method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top