How to exit from the search on clicking on Cancel button?
You need to implement the UISearchBarDelegate :
class ViewController: UIViewController, UISearchBarDelegate { @IBOutlet weak var searchBar: UISearchBar!
Set the search bar delegate to self
override func viewDidLoad() { super.viewDidLoad() searchBar.showsCancelButton = true searchBar.delegate = self
and then implement the butCancelSearchAction delegate function to do whatever you need to do to cancel the search action and reset the search text:
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { // Do some search stuff}func searchBarCancelButtonClicked(searchBar: UISearchBar) { // Stop doing the search stuff // and clear the text in the search bar searchBar.text = "" // Hide the cancel button searchBar.showsCancelButton = false // You could also change the position, frame etc of the searchBar }
class MyController: UIViewController, UISearchBarDelegate { // Called when search bar obtains focus. I.e., user taps // on the search bar to enter text. func searchBarTextDidBeginEditing(searchBar: UISearchBar) { searchBar.showsCancelButton = true } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.text = nil searchBar.showsCancelButton = false // Remove focus from the search bar. searchBar.endEditing(true) // Perform any necessary work. E.g., repopulating a table view // if the search bar performs filtering. }}
Try. It works fine.
class MyViewController: UIViewController, UISearchBarDelegate { func searchBarTextDidBeginEditing(_searchBar: UISearchBar) { searchBar.setShowsCancelButton(true, animated: true) //write other necessary statements } func searchBarCancelButtonClicked(_searchBar: UISearchBar) { searchBar.text = nil searchBar.setShowsCancelButton(false, animated: true) // Remove focus from the search bar. searchBar.endEditing(true) }}