Home > Software design >  Why will UITableViewController navigationItem.searchController not set in iOS?
Why will UITableViewController navigationItem.searchController not set in iOS?

Time:12-14

For some reason, when I set UITableViewController navigationItem.searchController with a UISearchController, it doesn't take it.

Here is my code:

let searchController = UISearchController(searchResultsController: nil)

if #available(iOS 11.0, *) {
    print("?", navigationItem.searchController)
    print("!", searchController)
    navigationItem.searchController? = searchController
    print("?", navigationItem.searchController)
} else {
    tableView.tableHeaderView = searchController.searchBar
}

Here is the debug window:

? nil
! <UISearchController: 0x105077600>
? nil

CodePudding user response:

This has nothing to do with search controllers or navigation items. It has to do with the Swift language. You've slammed accidentally into a little-known edge case in optional chain syntax. The problem is this line:

navigationItem.searchController? = searchController

I don't know what you think that means, but it doesn't mean that! Delete the question mark:

navigationItem.searchController = searchController
  • Related