Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 721
aji Avatar asked Apr 28 '15 16:04

aji


People also ask

How do you dismiss a keyboard when tapping outside Swift?

Via Tap Gesture This is the quickest way to implement keyboard dismissal. Just set a Tap gesture on the main View and hook that gesture with a function which calls view. endEditing . Causes the view (or one of its embedded text fields) to resign the first responder status.

How do you dismiss a keyboard?

Android devices have a solution; press the physical back button (provided on some mobile phones) or the soft key back button, and it closes the keyboard.


2 Answers

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) 
like image 72
Koray Birand Avatar answered Sep 19 '22 19:09

Koray Birand


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

Swift 4:

self.tableView.keyboardDismissMode = .onDrag 
like image 44
Dominic Smith Avatar answered Sep 18 '22 19:09

Dominic Smith