在Swift中自定义UISearchController和UISearchBar时委派问题

时间:2016-04-30 10:34:37

标签: ios objective-c swift delegates searchbar

在我的tableViewController中,我需要将搜索功能作为功能之一,并且它符合这些委托,其中一个是UISearchController委托的子类。

class MyTableViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate, CustomSearchControllerDelegate {

    var customSearchController: CustomSearchController!

    func addCustomSearchBar() {
        customSearchController = CustomSearchController(...)

        /* detail setting and add the customSearchBar */

        customSearchController.customDelegate = self
        customSearchController.searchResultsUpdater = self

        /* implement customDelegate method */

    func updateSearchResultsForSearchController(searchController: UISearchController) {
        guard let searchString = customSearchController.customSearchBar.text else {
        return
        }

        newArray = dataArray.filter({ (text) -> Bool in
        let text:NSString = text

        return (text.rangeOfString(searchString!, options: NSStringCompareOptions.CaseInsensitiveSearch).location) != NSNotFound
        })

        tableView.reloadData()
           /*-----------won't work-------------*/
        }

    }

我的UISearchController的子类如下,

class CustomSearchController: UISearchController, UISearchBarDelegate{
    var customSearchBar: CustomSearchBar! //subclass of UISearchBar
    var customDelegate: CustomSearchControllerDelegate!

        ...

    init(...) {
    self.mySearchBar(...)
    }

   func mySearchBar(...) {
       customSearchBar = CustomSearchBar(...)

       /* detail setting */

       customSearchBar.delegate = self
    }

    func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
        customDelegate.didStartSearching()
}


    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        customSearchBar.resignFirstResponder()
        customDelegate.didTapOnSearchButton()
} 


    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        customSearchBar.resignFirstResponder()
        customDelegate.didTapOnCancelButton()
}

如您所见,此子类有自己的委托来处理UISearchBarDelegate

问题是,为什么UISearchResultsUpdating委托方法不起作用?,我认为UISearchResultsUpdating委托也可以。

我知道我可以在我的UISearchController func searchBar(searchBar: UISearchBar, textDidChange: searchText: String)子类中实现UISearchBarDelegate方法,作为在搜索栏中输入文本时搜索的替代方法。

但我真的很想知道为什么它不会在这里工作,谢谢你帮助我。

如果有任何歧义,请在下面评论,再次感谢!

0 个答案:

没有答案