Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISearchBar : How to prevent Cancel Button from clearing text?

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.

like image 819
mavilein Avatar asked Feb 13 '14 18:02

mavilein


1 Answers

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
    }
}
like image 113
Alex Pretzlav Avatar answered Nov 16 '22 03:11

Alex Pretzlav