iOS, Swift 3 - UISearchBar disappears when I click

2019-08-06 17:28发布

问题:

I have a tableView in a containerView. Programmatically added a searchBar to it. Everything works fine, except for the case: When I tap on a cell, while the tableView is filtered by the searchBar, and then I return from the detailView (that was presented via push segue) and then I dismiss the searchBar (cancel button), then the searchBar disappears. Mysteriously, when I debug it on the console, the searchBar object is still there and it is still the headerView of the tableView... Anybody has an idea, what could cause this problem, and how to fix it?

Here is my relevant code:

In viewDidLoad:

self.searchController.searchResultsUpdater = self
self.searchController.delegate = self
self.searchController.dimsBackgroundDuringPresentation = false
self.searchController.hidesNavigationBarDuringPresentation = false
self.searchController.definesPresentationContext = false
self.tableView.tableHeaderView = self.searchController.searchBar

searchControllerDelegate:

func willPresentSearchController(_ searchController: UISearchController) {
    if let mpvc = self.parent as? MyPulleyViewController {
        mpvc.navigationController?.navigationBar.isTranslucent = true
    }
}


func willDismissSearchController(_ searchController: UISearchController) {
    if let mpvc = self.parent as? MyPulleyViewController {
        mpvc.navigationController?.navigationBar.isTranslucent = false
    }
}

(myPulleyViewController is the VC containing the containerView, self is the containerView's VC)

On the IB, the mpvc is set to Extend edges: Under Opaque Bars

Thanks for any help!

回答1:

I faced the same problem, I think this is iOS issue, I fixed it by making viewcontroller for Search Result :

   let searchVC = mainStoryboard.instantiateViewController(withIdentifier: identifier) as! SearchResultViewController
    let searchController = UISearchController(searchResultsController: searchVC)
    searchController.searchResultsUpdater = searchVC

and it works fine.