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

Solution 1:

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)

Solution 2:

I found it easier and simplier to use Table View for dismissal. (If you're using table view)

Swift 4:

self.tableView.keyboardDismissMode = .onDrag

Solution 3:

Tested and working!

func searchBarSearchButtonClicked(searchBar: UISearchBar) 
{
    searchActive = false;
    self.mySearchBar.endEditing(true)
}

Edit for Swift 4.2

func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
    {
        searchActive = false
        self.searchBar.endEditing(true)
    }

Solution 4:

 func searchBarSearchButtonClicked(searchBar: UISearchBar) {

        searchActive = false;
        searchProject.resignFirstResponder()
    }

This method will be invoked when user click search button on keyboard.So here we can dismiss keyboard.I think this is the right method.