How to make keyboard dismiss when i press out of searchbar on Swift?

aji picture aji · Apr 28, 2015 · Viewed 52.1k times · Source

I try to make my searchbar on swift, but i have a problem to dismiss keyboard on screen when i pressed out of searchbar. When i try with textfield it work perfectly fine with this code.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        self.view.endEditing(true)
    }   

It work when i press out of my textfield and then the keyboard is gone. I want to make like that with my searchbar, because when i use searchbar and use the same way like textfield, it doesn't work at all. Any reference or code is very useful for me.

Answer

Koray Birand picture Koray Birand · Apr 28, 2015

try this :

self.mySearchController.searchBar.endEditing(true)

replace mySearchController with your created controller name.. If you did not create it programmatically but instead you just dragged a search bar from library then IBoutlet your searchable to your class and reference it as:

self.mySearchBar.endEditing(true)