当前位置:  开发笔记 > 编程语言 > 正文

如何在单击"取消"按钮时退出搜索?

如何解决《如何在单击"取消"按钮时退出搜索?》经验,为你挑选了3个好方法。

我有一个带取消按钮的搜索栏.但是,当我单击"取消"按钮时,它不会关闭搜索栏.如何点击取消它会将搜索栏返回到第一个状态?

如果您有任何问题 - 请问我



1> Peter Todd..:

您需要实现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 
}



2> orangemako..:
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. 
    }
}



3> mumu..:

尝试.它工作正常.

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

推荐阅读
爱唱歌的郭少文_
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有