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:
|
1 2 3 |
-(BOOL)disablesAutomaticKeyboardDismissal{ return NO; } |
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
|
1 2 3 4 5 6 7 |
#import <Foundation/Foundation.h> @interface UINavigationController (ResponderFix) -(BOOL)disablesAutomaticKeyboardDismissal; @end |
UINavigationControllerResponderFix.m
|
1 2 3 4 5 6 7 8 9 |
#import "UINavigationControllerResponderFix.h" @implementation UINavigationController (ResponderFix) -(BOOL)disablesAutomaticKeyboardDismissal{ return NO; } @end |
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:
|
1 2 3 4 5 6 |
#ifdef __OBJC__ #import <UIKit/UIKit.h> #import <Foundation/Foundation.h> #import "UINavigationControllerResponderFix.h" #endif |
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
Powered by Facebook Comments