Search code examples
iosobjective-ckeyboarduisearchbarresignfirstresponder

Dismissing Keyboard FirstResponder problems


So i am making an app and am having some problems with dismissing the keyboard from UISearchBar and UITextFields. Here is the structure of my app:

NavigationController -> ViewC1 - (Modally)-> ViewC2 -(Modally) -> ViewC3

I have a search box in ViewC1, and when the "Search" button on the keyboard is pressed the keyboard is dismissed, this works fine. However if i return to ViewC1 after being in ViewC3 the keyboard no longer dismisses when the "Search" button is pressed. In the search bar delegate method i have put as follows:

- (void) searchBarSearchButtonClicked:(UISearchBar *)search
{
if ([search isFirstResponder]) {
    [search resignFirstResponder];
  } else {
    [search becomeFirstResponder];
    [search resignFirstResponder];
  }
}

This does not solve the problem and i am not sure why the keyboard is not dismissing. For reference, when returning to the original ViewC1, ViewC3 is dismissed as follows:

UIViewController *parent = self.presentingViewController;
[parent.presentingViewController dismissViewControllerAnimated:YES completion:nil];

Any help is appreciated, thanks.


Solution

  • Okay i figured out what the problem was. They first responder was being resigned but the keyboard was not disappearing because of a focus issue. There is a default behaviour on modal views to not dismiss the keyboard (which is not a bug apparently). So after returning from the modal view it was still having this behaviour (resigning first responder but not dismissing keyboard). The way i solved this was by placing the following code in both the modal views .m files:

    - (BOOL)disablesAutomaticKeyboardDismissal {
    return NO;
    }
    

    This solved it for me. Then by either using:

    [search resignFirstResponder];
    

    or

    [self.view endEditing: YES];
    

    The keyboard will dismiss fine!