UISearchBar : How to prevent Cancel Button from clearing text?

百般思念 提交于 2019-12-12 10:46:00

问题


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
    }
}


来源:https://stackoverflow.com/questions/21762859/uisearchbar-how-to-prevent-cancel-button-from-clearing-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!