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

前端 未结 10 1157
谎友^
谎友^ 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:37

    You need to implement the UISearchBarDelegate.

    The UISearchBarDelegate protocol defines the optional methods you implement to make a UISearchBar control functional. A UISearchBar object provides the user interface for a search field on a bar, but it’s the application’s responsibility to implement the actions when buttons are tapped. At a minimum, the delegate needs to perform the actual search when text is entered in the textField. Read this

    In Objective C

    - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    
         [self.searchDisplayController setActive:NO animated:YES];
    
    }
    

    In Swift :

    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    
        self.searchDisplayController.setActive(false, animated: true)
    }
    
    0 讨论(0)
  • 2021-02-07 01:40

    Try this:

    searchController.active = false
    
    0 讨论(0)
  • 2021-02-07 01:43

    Swift 3

    func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
        searchBar.showsCancelButton = true
        return true
    }
    
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        self.searchBar.endEditing(true)
        searchBar.resignFirstResponder()
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
    }
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        self.searchBar.endEditing(true)
        searchBar.showsCancelButton = false
        searchBar.resignFirstResponder()
    }
    
    The Cancel button appears only when the user start entering characters in the field.
    
    0 讨论(0)
  • 2021-02-07 01:44

    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) 
        }
    } 
    
    0 讨论(0)
提交回复
热议问题