swiftkeyboarduisearchbarsearchbaruisearchbardelegate

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


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 works 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.


Solution

  • 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)