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

11

64

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.

Ehrenberg answered 28/4, 2015 at 16:51 Comment(2)
You can find the answer in the link below: #24909466Dog
i had try that so i get my code for textfield and it works perfectly fine like what i say, but i have some problem when i have to use searchbar, because i can't make my keyboard dismiss when i touch another area outside my searchbarEhrenberg
B
90

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)
Bagpipe answered 28/4, 2015 at 17:37 Comment(10)
could you give me any clue how to get event on click outside my searchbar, because when i use textfield, i use function like what i write before and it works automatically to get event when i click outside my textfield. Can you help me to have function like that in searchbarEhrenberg
did you drag it from the library to your storyboard or created it from an inside of a class.. ?Bagpipe
i dragged it from my storyboardEhrenberg
I think your solution is fine. But i want to know what event that i get when i click outside my searchbar. If i know that event then i could take your suggestion inside it and it should be working.Ehrenberg
I assume you are using a tableview or a collection view under the search bar . they both have dismiss keyboard check box. You can use them.Bagpipe
did you try putting my line into your touchesBegan func. ? that should do it.Bagpipe
yes i put it inside my touchesBegan fun, but i think it just working with textsielddelegate, not with searcbar.Ehrenberg
I created a sample project for you, check it out. koraybirand.co.uk/download.asp?usr=test&file=/download/…Bagpipe
I think i realize somethink, i should reconnect with every view first because i make another view parent and searchbar as a child, but your solution is work if i use a simple one, thankEhrenberg
I realize it from this #7482766Ehrenberg
H
44

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

Swift 4:

self.tableView.keyboardDismissMode = .onDrag
Heyday answered 2/4, 2019 at 3:32 Comment(2)
I didn't even know this existed, thanks for sharing Dominic, worked like a charm and a nice addition to also resigning the keyboard through the search button.Arst
This should be the accepted answer. BTW the Contacts app on iPhone seems to use exactly this mode.Cystotomy
D
33

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)
    }
Delaryd answered 21/9, 2015 at 18:38 Comment(1)
Why ignore the searchBar parameter?Coraleecoralie
C
11
 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.

Chitkara answered 30/7, 2015 at 9:51 Comment(0)
D
10

Firstly, Apple's UISearchBarDelegate is the correct solution to hide keyboard when users click a search button while UISearchBar's instance is the first responder (learn UIResponder). In short, searchBarSearchButtonClicked(_:) is what you need for this task.

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchBar.resignFirstResponder() // hides the keyboard.
    doThingsForSearching()
}

If it doesn't work, check, does your controller conform to UISearchBarDelegate and secondly, does UISearchBarDelegate know about your class implementation (if you don't quite understand what am I talking about, you should learn delegation pattern starting to read here):

class YourAwesomeViewController: UIViewController, UISearchBarDelegate { // pay attention here

    @IBOutlet weak var yourSearchBar: UISearchBar!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.yourSearchBar.delegate = self // and it's important too
    }
}

Further, if you need to hide the keyboard touching outside of search bar without touching the search button (the user may change his mind to search something), UITapGestureRecognizer is a simple way too to deal with that.

  1. Ctrl-drag a Tap Gesture Recognizer from the Object Library to your View Controller.

enter image description here

  1. Ctrl-drag the recently added Tap Gesture Recognizer from the document outline in the storyboard to your class implementation as IBAction.

enter image description here

  1. Finally, write a code:

@IBAction func tapToHideKeyboard(_ sender: UITapGestureRecognizer) { self.yourSearchBar.resignFirstResponder() }

Also, don't forget to create @IBOutlet for the search bar to have an access inside your class implementation.

Both variants above work well in my project.

Daliadalila answered 6/10, 2017 at 1:59 Comment(0)
T
8

Swift 4+:

You can try, creating a tap gesture and add in the self.view

let singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.singleTap(sender:)))
singleTapGestureRecognizer.numberOfTapsRequired = 1
singleTapGestureRecognizer.isEnabled = true
singleTapGestureRecognizer.cancelsTouchesInView = false
self.view.addGestureRecognizer(singleTapGestureRecognizer)

and in selector func you call self.searchBar.resignFirstResponder

@objc func singleTap(sender: UITapGestureRecognizer) {
    self.searchBar.resignFirstResponder()
}
Telluride answered 14/4, 2018 at 16:47 Comment(0)
R
5
class MaCaveViewController: UIViewController, UISearchBarDelegate {
    
    @IBOutlet weak var searchBar: UISearchBar!

    override func viewDidLoad() {
        super.viewDidLoad()
        searchBar.delegate = self
    }

    // When button "Search" pressed
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar){
        print("end searching --> Close Keyboard")
        self.searchBar.endEditing(true)
    }
}

This works very well for me.

Renae answered 12/2, 2018 at 10:59 Comment(1)
This answer is the only one I got to work first time. (Using Swift 5). Thank you!Magavern
B
5

You can use a general UIViewController extension

  1. Just add a new swift file on the project and paste the following code snippet

Code

extension UIViewController {

    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard(_:)))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

    @objc func dismissKeyboard(_ sender: UITapGestureRecognizer) {
        view.endEditing(true)

        if let nav = self.navigationController {
            nav.view.endEditing(true)
        }
    }
 }
  1. Now call hideKeyboardWhenTappedAround() from viewDidLoad method where you want keyboard hiding feature.
Brusque answered 21/9, 2018 at 9:30 Comment(0)
R
1

we can do this with following methods

    func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
        searchBar.showsCancelButton = true;
    }

    func searchBarTextDidEndEditing(searchBar: UISearchBar) {
        searchBar.showsCancelButton = false;
    }
Rapier answered 22/11, 2016 at 14:27 Comment(0)
M
0

This works for me in Swift 4

   func searchBarSearchButtonClicked(_ searchBar: UISearchBar){

    self.searchBar.endEditing(true)

    }
Manteau answered 16/6, 2019 at 18:19 Comment(1)
why are you using "self" -- the searchBar object that is active is being passed into this delegate's method. "searchBar.endEditing(true)" works just fine. with self, you are referencing your outer declaration (which may or may NOT be the same instance).Jarred
S
0

it is more recomended than searchBar.endEditing(true) self.mySearchController.searchBar.resignFirstResponder()

Sateia answered 15/7, 2023 at 17:25 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Immaculate

© 2022 - 2025 — McMap. All rights reserved.