updatesearchresultsforsearchcontroller not called

2019-07-19 19:43发布

问题:

Does anyone know why its not being called here? Thanks. I think I set up the delegate correctly.

class LocationSearchController: UIViewController, UISearchResultsUpdating, UINavigationBarDelegate, UISearchControllerDelegate {

let navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 44))

var locationSearchController: UISearchController!

override func viewDidLoad() {
    super.viewDidLoad()


    locationSearchController = UISearchController(searchResultsController: nil)

    self.locationSearchController.loadViewIfNeeded()

    //sets up search controller
    self.locationSearchController.searchResultsUpdater = self
    self.locationSearchController.delegate = self
    definesPresentationContext = true
    //self.videoSearchController.searchBar.delegate = self

    //sets up nav bar
    navigationBar.backgroundColor = UIColor.blackColor()
    navigationBar.delegate = self



    navigationItem.titleView = locationSearchController.searchBar
    //leftButton.title = "Left"
    //navigationItem.leftBarButtonItem = leftButton
    navigationBar.items = [navigationItem]

    self.view.addSubview(navigationBar)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func updateSearchResultsForSearchController(searchController: UISearchController) {
    print("search results updated 2")
}

}

Any ideas would be much appreciated. I've searched for a little while and I failed to find a question about this that was answered.

回答1:

I ran into the same issue with iOS8. This is a workaround, but it will fix this.

  • Have LocationSearchController implement UISearchBarDelegate
  • Add this line in viewDidLoad:

    locationSearchController.searchBar.delegate = self
    
  • Add this method:

    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        updateSearchResultsForSearchController(locationSearchController)
    }