Keyboard out of My Mind

Four years ago (!) I wrote up the best practices I could find for dealing with the appearance and disappearance of the keyboard on iOS.

Since then, did they break? Any guesses?

Anyone?

Actually, they mostly still work.

If you’ll remember, the big problem was that iOS simply wouldn’t tell us when we were rotating. Instead, the news was delivered in separate, unconnected keyboard-will-hide and keyboard-will-show notifications.

We got around that by, in the will-show notification, starting our animation from the current point (via UIViewAnimationOptionBeginFromCurrentState), instead of from all the way at the bottom of the screen.

On iPhone for iOS 10, as far as I can tell, that trick doesn’t work anymore. (It still does on iPad.) Your animation begins at the bottom of the screen, out of sync with the actual keyboard movement, no matter what options you set.

But in the meantime, iOS has introduced an API that does give us access points both for the start and end of a rotation animation, viewWillTransitionToSize:​withTransitionCoordinator:.

This method is called at the start of the rotation, so that’s one access point accounted for.

And if you call the transition coordinator’s animateAlongsideTransition:​completion: method with a completion block inside it, per Apple’s best practices, the completion block is where you can do things guaranteed to occur after the rotation is over. So that’s the second access point accounted for.

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    // BEGINNING OF ROTATION
    [coordinator animateAlongsideTransition:^(id  _Nonnull context) {
    } completion:^(id  _Nonnull context) {
        // END OF ROTATION
    }];
}

Now, this API is meant to be more general-purpose than just rotation: it’s called for every multitasking size change on iPad. But we can find out whether it is a rotation transition by checking whether the new size’s width and height are the same as the old size’s height and width. If it is, now we set a flag that, in our will-hide logic, can be used to not animate at all under these circumstances.

So that’s it! One fairly small fix.

However, since it has been four years (!), I’ve made a number of changes beyond that in the GitHub project:

  • A new project, Corrected Keyboard Schmeeboard2, has been updated to Xcode 8 standards, Auto Layout, and more, without otherwise changing the code.
  • A second new project, Corrected Keyboard Schmeeboard3, has the iOS 10 iPhone rotation fix on top of the changes from 2.
  • And the last new project, Corrected Keyboard Schmeeboard4, converts the whole thing into Swift.

I’ll have more to say about Swift in future posts.