0

I'm trying to recreate the search screen in Settings > General > iPhone Storage > search. It's a modally presented screen with a UISearchController in the navigation bar that is always active, the keyboard appears after the screen appears, and tapping Cancel dismisses the screen rather than deactivating the search mode.

The problem I'm experiencing is I cannot get the search controller to be active until viewDidAppear, so you can see the navigation bar throughout the presentation, then after it appears the search bar moves up into the navigation bar. It's desired to always be active, but setting isActive = true in viewDidLoad does not do anything. I also tried searchController.searchBar.becomeFirstResponder() but this does not work even in viewDidAppear - has to be delayed via DispatchQueue.main.asyc.

Someone indicated here they believe this is because the search interface hasn't been fully initialized or something. How can we create an always active search controller like the mentioned Settings screen does?

override func viewDidLoad() {
    super.viewDidLoad()
    
    searchController.delegate = self
    searchController.searchResultsUpdater = self
    searchController.obscuresBackgroundDuringPresentation = false
    searchController.searchBar.delegate = self
    navigationItem.searchController = searchController
    definesPresentationContext = true
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    
    //FIXME: Works, but delay is undesirable - search controller should be active initially
    searchController.isActive = true

    //OR
    DispatchQueue.main.async {
        self.searchController.searchBar.becomeFirstResponder()
    }
}
Jordan H
  • 52,571
  • 37
  • 201
  • 351

1 Answers1

0

Try this in vieDidLoad or viewWillAppear

    DispatchQueue.main.async {
        UIView.performWithoutAnimation {
            self.searchController.isActive = true
        }
    }
user25917
  • 797
  • 7
  • 18
  • This did not work, this still results in seeing the navigation bar throughout the presentation, then after it finishes animating up then the search bar moves into the navigation bar. – Jordan H Jul 22 '21 at 14:34
  • I see. Because I use the custom transition so that animation is not noticeable. I suggest using the search bar in the `titleView` directly wIthout any tweak. – user25917 Jul 23 '21 at 03:13