如何让 UISearchController 等到搜索被点击

How to have UISearchController wait until search is clicked

我正在尝试在我的 SWIFT 代码中实现搜索。我希望它在执行任何操作之前等到单击搜索按钮。到目前为止我所拥有的。

func updateSearchResultsForSearchController(searchController: UISearchController)
{
    self.filteredCats.removeAll(keepCapacity: false)
    filteredCats = art.filter{
        [=10=].sarticleTitle.lowercaseString.rangeOfString(searchController.searchBar.text!.lowercaseString) != nil
    }
        print(searchController.searchBar.text)
        self.tableView.reloadData()
}

它会在用户输入内容后打印出所有信息。我希望它等到单击搜索按钮或用户完成所有输入后。

使用UISearchBarDelegate方法searchBarSearchButtonClicked(_:)Reference

class MySearchController:UISearchController, UISearchBarDelegate {

    override init(searchResultsController: UIViewController?) {
        super.init(searchResultsController: searchResultsController)
        // Set the searchbar delegate
        self.searchBar.delegate = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        // Start the search
    }

}

重要的是,请确保您告诉 UISearchBar 您希望 UISearchController 成为它的代表,上面是一个 un-tested 示例,您的确切初始化可能会有所不同。

实施 "searchController.searchBar.delegate" & "searchBarSearchButtonClicked" 方法

self.searchController.searchBar.delegate = self; 

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    //enter your search code
}

你应该像这样设置委托你的视图控制器。

var resultSearchController = UISearchController()
resultSearchController.searchBar.delegate = self

extension ViewController: UISearchBarDelegate {
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        print("search button click")
    } 
}