Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updateSearchResults() not getting called

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()
}
like image 922
Molly Avatar asked Jan 10 '17 03:01

Molly


3 Answers

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 :)

like image 53
Molly Avatar answered Nov 09 '22 00:11

Molly


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

like image 43
ruwan800 Avatar answered Nov 09 '22 00:11

ruwan800


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.

like image 4
Noodledew Avatar answered Nov 09 '22 01:11

Noodledew