updateSearchResults() 没有被调用

7

我在 Stack Overflow 上阅读了类似的问题和解决方案,但没有一种方法能够解决我的问题。我正在使用自定义搜索控制器和自定义搜索栏,但是 func updateSearchResults(for searchController: UISearchController) 函数没有被调用。

    var customSearchController: CustomSearchViewController!

CustomSearchViewController: 在ViewDidLoad()中

customSearchController = CustomSearchViewController(searchResultsController: ***nil***, searchBarFrame: CGRect(x: 0.0, y: 0.0, width: searchTableView.frame.size.width, height: 44.0), searchBarFont: UIFont(name: "HelveticaNeue", size: 16.0)!, searchBarTextColor: UIColor.purple, searchBarTintColor: UIColor.white)

customSearchController.searchResultsUpdater  = self
customSearchController.definesPresentationContext = true
customSearchController.customSearchBar.placeholder = "What are you looking for?"
customSearchController.customSearchBar.backgroundColor = UIColor.white
customSearchController.customSearchBar.sizeToFit()
customSearchController.customSearchBar.resignFirstResponder()
customSearchController.customSearchBar.showsCancelButton = true
customSearchController.customSearchBar.delegate = self

没有被调用::(
func updateSearchResults(for searchController: UISearchController) {
    filtered.removeAll()
    filtered = searchArray.filter({ (text) -> Bool in
        let tmp: NSString = text as NSString
        let range = tmp.range(of: customSearchController.customSearchBar.text!, options: NSString.CompareOptions.caseInsensitive)
        return range.location != NSNotFound
    })
    self.searchTableView.reloadData()
}

4个回答

11
经过几个小时的努力,我最终通过使用以下方法解决了问题: 使用func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) - UISearchBarDelegate代理方法,而不是updateSearchResults() - UISearchResultsUpdating代理方法。 希望能对有需要的人有所帮助 :)

7

1
当然可以!否则一旦超出作用域,它就会被释放。 - Jason Silver

4

看起来你没有设置这个:

searchController.searchResultsUpdater = self

确保这是最后一个命令,以避免出现错误。至少对我来说,这个命令可以完成任务。


这不是答案...请参考:https://stackoverflow.com/a/46781890/1511978 - Vincil Bishop

0

但是也许你的问题在于你调用了那个:

navigationItem.titleView = searchController.searchBar

相反,你应该这样做:

navigationItem.searchController = searchController

你能提供一个原因,说明这会有所帮助吗? - Artjom B.
实际上,我尝试了这两种情况,发现第二种情况可行,但第一种情况不行。 - Mohanad Refaai
我认为原因在于,在第一个情况下,搜索控制器没有添加到视图中(仅有搜索栏),因此我无法监听其更改,因此方法“updateSearchResults”将不会被调用。 - Mohanad Refaai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接