How to exit from the search on clicking on Cancel button?

前端 未结 10 1159
谎友^
谎友^ 2021-02-07 01:22

I have a search bar with cancel button. But when I click on Cancel button it doesn\'t close the search bar. How can I make that on click on Cancel it will return search bar to t

10条回答
  •  甜味超标
    2021-02-07 01:36

    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 
    }
    

提交回复
热议问题