UISearchController cannot become first responder when switching to a search tab

I would like my users to be able to switch to the search tab (in the sidebar) on iPad and immediately start typing. This is not possible. Calling becomeFirstResponder in viewDidLoad and viewWillAppear does not work. Only in viewDidAppear it does, but that comes with a significant delay between switching to the tab and the search field becoming active. Is there something else I can do?

FB19588765

let homeTab = UITab(
            title: "Home",
            image: UIImage(systemName: "house"),
            identifier: "Home"
        ) { _ in
            UINavigationController(rootViewController: ViewController())
        }
        
        let searchTab = UISearchTab { _ in
            UINavigationController(rootViewController: SearchViewController())
        }

        let tabBarController = UITabBarController(tabs: [
            homeTab, searchTab
        ])
        tabBarController.mode = .tabSidebar
class SearchViewController: UIViewController {
    
    let searchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = .systemBackground
        
        self.title = "Search"
               
        self.navigationItem.searchController = searchController
               
        self.navigationItem.preferredSearchBarPlacement = .integratedCentered
         
        searchController.becomeFirstResponder() // Does not work.
        searchController.searchBar.becomeFirstResponder() // Does not work.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        searchController.searchBar.becomeFirstResponder() // Does not work.
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        searchController.searchBar.becomeFirstResponder() // Works. But comes with a significant delay.
    }
}
Answered by ps3zocker in 853541022

Setting isActive does not seem to anything, at least not in the sidebar context. But it has pushed me in the right direction. This seems to work.

override func viewIsAppearing(_ animated: Bool) {
    super.viewIsAppearing(animated)
    searchController.searchBar.becomeFirstResponder()
}

Instead of trying to make the search bar the first responder, activate the search controller with isActive = true. Try that in viewWillAppear or viewIsAppearing.

Accepted Answer

Setting isActive does not seem to anything, at least not in the sidebar context. But it has pushed me in the right direction. This seems to work.

override func viewIsAppearing(_ animated: Bool) {
    super.viewIsAppearing(animated)
    searchController.searchBar.becomeFirstResponder()
}
UISearchController cannot become first responder when switching to a search tab
 
 
Q