iPhone: Hide Keyboard on App Did Enter Background or View Did Disappear

Viewed 9278

I have a UISearchBar which when clicked, shows the keyboard. However if the user presses the home button while the keyboard is shown and then goes back into the app, the keyboard is still visible. How can I hide th keyboard when the app closes/enters background?

I've tried the following in viewDidDisappear:

[eventSearchBar resignFirstResponder];

[eventSearchBar endEditing:YES];

I've also tried this in the delegate in appDidEnterBackground:

[self.rootController.navigationController.view endEditing:YES];

None of these worked.

6 Answers

Solution in swift 3.2 Version

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(hideTextField), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    func hideTextField(){
        eventSearchBar.endEditing(true)
    }

The best way is to put window?.endEditing(true) in applicationWillResignActive on AppDelegate:

func applicationWillResignActive(_ application: UIApplication) {
    window?.endEditing(true)
}
Related