UISearchBar : How to prevent Cancel Button from cl

2019-06-20 17:27发布

问题:

I have a screen with an UISearchBar within my app. It might be that there is already text in the searchbar, when the user enters the screen. If the user then taps into the field and then taps cancel, the content of the searchbar should not be cleared.

Is this achievable? I tried to implement searchBarCancelButtonClicked, but my modifications to the text property were ignored and the text field was still cleared.

回答1:

I ran in to this same problem and solved it by manually tracking the state of whether the cancel button was pressed. If it is, reset the text when the searchBar ends editing, as modifying searchBar.text in searchBarCancelButtonClicked doesn't work:

This is what I did in my UISearchBarDelegate class:

var searchTerms = ""
var searchWasCancelled = false

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    searchWasCancelled = false
}

func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    searchWasCancelled = true
}

func searchBarTextDidEndEditing(searchBar: UISearchBar) {
    if searchWasCancelled {
        searchBar.text = self.searchTerms
    } else {
        searchTerms = searchBar.text
    }
}