本文介绍了UISearchBar:如何防止取消按钮清除文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我的应用中有一个带有 UISearchBar 的屏幕。当用户进入屏幕时,搜索栏中可能已存在文本。 如果用户然后点击该字段然后点击取消,则不应清除搜索栏的内容。

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.

这是否可以实现?我尝试实现 searchBarCancelButtonClicked ,但我对text属性的修改被忽略,文本字段仍然被清除。

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

推荐答案

我遇到了同样的问题并通过手动跟踪是否按下取消按钮的状态解决了这个问题。如果是,请在searchBar结束编辑时重置文本,因为在 searchBarCancelButtonClicked 中修改 searchBar.text 不起作用:

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:

这是我在 UISearchBarDelegate 类中所做的:

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

这篇关于UISearchBar:如何防止取消按钮清除文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 08:12