UISearchController取消按钮不可点击

时间:2018-04-30 22:15:27

标签: ios swift uisearchcontroller cancel-button

有很多问题/答案,但不幸的是,它们都没有。

我有一个UICollectionViewController的子类,我希望它的collectionView项可以搜索。因此,我使用UISearchController但处理collectionView中已过滤的self项,因此将searchResultsController设置为nil。

class CollectionViewController: UICollectionViewController {

    var searchController: UISearchController!

    override func viewDidLoad() {

        super.viewDidLoad()

        self.becomeFirstResponder()

        searchController = UISearchController(searchResultsController: nil)
        searchController.delegate = self
        searchController.searchBar.delegate = self
        searchController.searchBar.isUserInteractionEnabled = true

        navigationItem.searchController = searchController

    }

}      

我按如下方式实现了所需的委托方法:

extension CollectionViewController:: UISearchControllerDelegate {
}

extension CollectionViewController:: UISearchBarDelegate {

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        collectionView?.reloadData()
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        print("searchBarCancelButtonClicked")
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        print("searchBarSearchButtonClicked")
    }

    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        print("searchBarTextDidEndEditing")
        collectionView?.reloadData()
    }

}

我可以在搜索栏中输入文字,过滤我的馆藏视图,并在输入文字时成功重新加载。此外,我可以点击键盘上的“搜索”,它会调用searchBarSearchButtonClicked方法。

enter image description here

但是,尽管Cancel按钮可见(见上文),但它似乎不可点击。因此,searchBarCancelButtonClicked方法不会被调用。

我在这做错了什么,拜托?

1 个答案:

答案 0 :(得分:2)

确保在宣布代表

后致电definesPresentationContext = true
class CollectionViewController: UICollectionViewController {

    var searchController: UISearchController!

    override func viewDidLoad() {

        super.viewDidLoad()

        self.becomeFirstResponder()

        searchController = UISearchController(searchResultsController: nil)
        searchController.delegate = self
        searchController.searchBar.delegate = self

        self.definesPresentationContext = true .  // ADD 

        searchController.searchBar.isUserInteractionEnabled = true

        navigationItem.searchController = searchController

    }

}