Disappearing UISearchController in a TableViewCont

2019-05-23 01:20发布

问题:

I have made a UITableView Controller with a UISearchBar as the Table's header.

I have then embedded this View Controller into a UINavigationController, as the root view controller.

Now, when I tap on the Search Bar, the SearchBar seems to disappears and displays a white screen. The keyboard appears, but there is no Search Bar. The Table View can scroll, but the search bar has simply vanished.

When I implement this UITableViewController without the Navigation Controller, it works perfectly. But something about the Navigation Controller is borking everything up.

回答1:

I've had the same issue that was sometimes happening, especially with table view of small number of rows (less than 50). It appears the searchBar is removed from the view hierarchy, precisely from the container view that is a child of the UISearchControllerView.

I've found a workaround to manually add back the searchbar as a subview of the UISearchControllerView container child. This is implemented in the delegate function (from UISearchControllerDelegate) didPresentSearchController:

func didPresentSearchController(searchController: UISearchController) {
    if searchController.searchBar.superview == nil {
        for searchCtrlChildView in searchController.view.subviews {
            if searchCtrlChildView.frame.origin == CGPoint(x: 0, y: 0) { //Discriminate if by chance there was more than one subview
                searchCtrlChildView.addSubview(searchController.searchBar)
                break
            }
        }
    }
}

I've also filed a radar to Apple on this as it is not fixed in iOS 8.4



回答2:

Check the way I had my searchBar it in viewDidLoad

I have my viewController embedded in NavigationController too

My code (hope it helps) :

class myTableViewController: UITableViewController,UISearchResultsUpdating,UISearchControllerDelegate,UISearchBarDelegate

override func viewDidLoad() {
    super.viewDidLoad()
    self.resultSearchController = ({
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.sizeToFit()
        self.tableView.tableHeaderView = controller.searchBar
        return controller
    })()