Modal Dialog Does Not Dismiss Keyboard

I am running into an issue where the keyboard does not get dismissed when leaving a UITextField or UITextView in a UIModalPresentationFormSheet. In addition, I've created a large button to serve as the view's background so if the user taps outside the fields it gets triggered. I am using the same code in a regular view controller, and it works as expected. In the modal view controller it does nothing. Any suggestions would be appreciated.

- (BOOL)textFieldShouldReturn:(id)sender {  
 [titleTextField resignFirstResponder];
 return YES;
}

- (BOOL)textViewShouldReturn:(id)sender {  
 [synopsisTextView resignFirstResponder];
 return YES;
}

- (IBAction)textFieldDoneEditing:(id)sender {  
 [sender resignFirstResponder];
} 

- (IBAction)textViewDoneEditing:(id)sender {  
 [sender resignFirstResponder];
} 

- (IBAction)backgroundClick:(id)sender {  
 [titleTextField resignFirstResponder];
 [synopsisTextView resignFirstResponder];
}

Solution 1:

Overriding disablesAutomaticKeyboardDismissal to return NO as below fixed the same problem of mine. You should put this code to your view controller, from which you initiate the keyboard:

- (BOOL)disablesAutomaticKeyboardDismissal {
    return NO;
}

Also, check this SO question if you want to get a detailed explanation.

Solution 2:

For those having trouble with UINavigationController, I think there is a better solution than a category on UIViewController. We should change the behavior of UINavigationController to ask its topViewController (in my opinion, this is how all ViewController containers should handle this).

@implementation UINavigationController (DelegateAutomaticDismissKeyboard)
- (BOOL)disablesAutomaticKeyboardDismissal {
    return [self.topViewController disablesAutomaticKeyboardDismissal];
}

Solution 3:

If you're presenting a modal view with presentation style "form sheet", Apple apparently does not dismiss the keyboard, thinking that they don't want the keyboard to jump in and out where a user will be doing a lot of editing (i.e. "forms"). The fix would be to change presentation style or live with it.

Solution 4:

If you implement the UITextFieldDelegate protocol you can inadvertently cause this behavior if you do text validation. If your validation codes returns false from textFieldShouldEndEditing when the text is invalid, the field can't relinquish it's firstResponder status and the keyboard will remain on screen in the next view.

More details at UITextField's keyboard won't dismiss. No, really