resignFirstResponder ‘bug’ in UIModalPresentationFormSheet

So err… this has been killing me for a while.
The keyboard on my UIModalPresentationFormSheet would not Fuck Off!

The problem

I presented a modal view controller with a modalPresentationStyle of UIModalPresentationFormSheet, but further to that, my view controller was presented within a UINavigationController.

Here’s a quote from Apple:

[with regard to UIModalPresentationFormSheet] To avoid frequent in-and-out animations, the keyboard will sometimes remain on-screen even when there is no first responder. This is not a bug.

Okay, now I understand the reasons why they build this caveat into the code in the first place, but dear God this gave me a headache. I only used UIModalPresentationFormSheet because it had the frame properties I desired for my view.

The “Solution”

As of iOS 4.2 Apple have been kind enough to provide a disablesAutomaticKeyboardDismissal method for us to override. It defaults to YES and what we need to do is change is so it defaults NO. Embed this code in your UIViewController:

This should fix the issue by forcing iOS to listen to your resignFirstResponders and not cancel them out.

Here’s where it got a little complicated for me…
I presented my view controller inside a navigation controller. This means that the above fix does not work!

UINavigationController Category

I had to delve into categories in order to get this to work.

I’ve never had to use a Category before, so I first needed to understand what they were and how to use them without breaking anything else.

Here’s what I created:

UINavigationControllerResponderFix.h

UINavigationControllerResponderFix.m

Above you can see I created a category for UINavigationController. What this does is make an adjustment for every instance of UINavigationController, wherever I include the #import statement for this interface. This particular category overrides the disablesAutomaticKeyboardDismissal method and forces it to become NO.

How do I use this project-wide I hear you ask! You’ll need to modify your [applicationname]-Prefix.pch file:

Now, every file will be forced to import the UINavigationControllerResponderFix file, creating a happier environment for everyone.
Your resignFirstResponder statements should now work.

If you’d like to download the file for yourself, here it is: UINavigationControllerResponderFix

Comments

comments

Powered by Facebook Comments