updateSearchResults() not getting called

拈花ヽ惹草 提交于 2020-05-28 18:07:27

问题


I have read similar problems and solutions on SO. But none seems to solve my problem. I am using Custom Search Controller and Custom Search Bar and func updateSearchResults(for searchController: UISearchController) is not getting called.

    var customSearchController: CustomSearchViewController!

CustomSearchViewController: In 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

Not getting called: :(

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

回答1:


After struggling for hours, I was able to solve it by using: func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) - UISearchBarDelegate delegate method.

instead of updateSearchResults() - UISearchResultsUpdating delegate method

Hope it helps someone :)




回答2:


I had to declare UISearchController instance within the class scope. See this answer. https://stackoverflow.com/a/46781890/1511978

Previously I had declared it within the viewDidLoad method




回答3:


It looks like you did not set this:

searchController.searchResultsUpdater = self

Make sure this is the last command to avoid getting errors. At least this did the job for me.




回答4:


But maybe your problem was that you call that:

navigationItem.titleView = searchController.searchBar

Instead, you should do that:

navigationItem.searchController = searchController


来源:https://stackoverflow.com/questions/41560794/updatesearchresults-not-getting-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!