我有一个带取消按钮的搜索栏.但是,当我单击"取消"按钮时,它不会关闭搜索栏.如何点击取消它会将搜索栏返回到第一个状态?
如果您有任何问题 - 请问我
您需要实现UISearchBarDelegate:
class ViewController: UIViewController, UISearchBarDelegate { @IBOutlet weak var searchBar: UISearchBar!
将搜索栏委托设置为self
override func viewDidLoad() { super.viewDidLoad() searchBar.showsCancelButton = true searchBar.delegate = self
然后实现butCancelSearchAction委托函数,以执行取消搜索操作和重置搜索文本所需的任何操作:
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { // Do some search stuff } func searchBarCancelButtonClicked(searchBar: UISearchBar) { // Stop doing the search stuff // and clear the text in the search bar searchBar.text = "" // Hide the cancel button searchBar.showsCancelButton = false // You could also change the position, frame etc of the searchBar }
class MyController: UIViewController, UISearchBarDelegate { // Called when search bar obtains focus. I.e., user taps // on the search bar to enter text. func searchBarTextDidBeginEditing(searchBar: UISearchBar) { searchBar.showsCancelButton = true } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.text = nil searchBar.showsCancelButton = false // Remove focus from the search bar. searchBar.endEditing(true) // Perform any necessary work. E.g., repopulating a table view // if the search bar performs filtering. } }
尝试.它工作正常.
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) } }