Wednesday, March 26, 2014

Listening To Keyboard Events

When dismissing the keyboard is part of an animated transition in an iOS application, the keyboard dismisses itself at its own pace while the other animations take effect at the same time. Sometimes this effect isn't too bad.

But sometimes we can make it better.

Sometimes the animations we create are supposed to be slick. Sometimes you may want to override the default animations a UINavigationController uses. If you're going to do all that work, you probably want the animation effect to be sharp, crisp, and exactly to your specifications. I know I would.

In these cases, the speed at which the keyboard dismisses itself can be distracting to the rest of the transition animations. I needed to order my animations precisely so I had to be able to initiate them around the movement of the keyboard. Enter our friends the keyboard notification events: UIKeyboardWillShowNotification, UIKeyboardDidShowNotification, UIKeyboardWillHideNotification, and UIKeyboardDidHideNotification. 

Using the NSNotificationCenter class methods we can subscribe observers to different notification events. So in the object that is controlling the animation effects - in my case a UIViewController subclass - you can do the following:

- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    // subscribe to the keyboard show and hide notification events
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
}

// ...

- (void) keyboardDidShow: (NSNotification *)notification
{
    // do awesome stuff here
}

- (void) keyboardDidHide: (NSNotification *)notification
{
   // continue being awesome  
}

// don't forget to stop listening when we've bounced
- (void) viewWillDisappear:(BOOL)animated
{
    // stop listening to keyboard notifications
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [super viewWillDisappear:animated];
}

In my case, my awesomeness would be to examine the animation state of my UIViewController subclass to see if it was in the middle of performing some kind of animation and then follow through with the animations that needed to happen either before or after the keyboard was shown or hidden, respectively.

Go forth and conquer that keyboard!

No comments:

Post a Comment