I am experiencing a problem with the new way of adding search bar to the navigation item.
As you can see in the picture below, there are two UIViewControllers one af
The accepted answer does solve the problem for some situations, but I was experiencing it resulting in the complete removal of the navigationItem
in the pushed view controller if the first search bar was active.
I've come up with another workaround, similar to the answer by stu, but requiring no meddling with constraints. The approach is to determine, at the point of the segue, whether the search bar is visible. If it is, we instruct the destination view controller to make its search bar visible from load. This means that the navigation item animation behaves correctly:
Assuming the two view controllers are called UIViewController1
and UIViewController2
, where 1
pushes 2
, the code is as follows:
class ViewController1: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
let searchController = UISearchController(searchResultsController: nil)
searchController.obscuresBackgroundDuringPresentation = false
navigationItem.searchController = searchController
definesPresentationContext = true
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let viewController2 = segue.destination as? ViewController2, let searchController = navigationItem.searchController {
// If the search bar is visible (but not active, which would make it visible but at the top of the view)
// in this view controller as we are preparing to segue, instruct the destination view controller that its
// search bar should be visible from load.
viewController2.forceSearchBarVisibleOnLoad = !searchController.isActive && searchController.searchBar.frame.height > 0
}
}
}
class ViewController2: UITableViewController {
var forceSearchBarVisibleOnLoad = false
override func viewDidLoad() {
super.viewDidLoad()
let searchController = UISearchController(searchResultsController: nil)
searchController.obscuresBackgroundDuringPresentation = false
navigationItem.searchController = searchController
// If on load we want to force the search bar to be visible, we make it so that it is always visible to start with
if forceSearchBarVisibleOnLoad {
navigationItem.hidesSearchBarWhenScrolling = false
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// When the view has appeared, we switch back the default behaviour of the search bar being hideable.
// The search bar will already be visible at this point, thus achieving what we aimed to do (have it
// visible during the animation).
navigationItem.hidesSearchBarWhenScrolling = true
}
}