Cannot set searchBar as firstResponder

前端 未结 21 1856
别跟我提以往
别跟我提以往 2020-11-30 01:33

I have a searchBar I\'m setting in a tableviewcontroller. i\'ve referenced this similar question UISearchBar cannot become first responder after UITableView did re-appear bu

21条回答
  •  萌比男神i
    2020-11-30 02:14

    Xcode 11.4, Swift 5.2

    If you just want the SearchBar to appear but not activate the TextField & keyboard. There is no need to dispatch it to the main thread.

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        searchController.isActive = true
    }
    

    If you want the TextField to activate with the keyboard, then you do need to call it on the main thread. There is no need to make the SearchController active, this happens automatically.

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        DispatchQueue.main.async {
            self.searchController.searchBar.becomeFirstResponder()
        }
    }
    

    This may depend on how you configure your SearchController. This is how I configure mine:

    // Defined in class
    let searchController = UISearchController(searchResultsController: nil)
    
    // Called in viewDidLoad
    navigationItem.searchController = searchController
    searchController.searchResultsUpdater = self
    searchController.searchBar.scopeButtonTitles = ["A", "B"]
    searchController.searchBar.delegate = self          
    searchController.obscuresBackgroundDuringPresentation = false
    

提交回复
热议问题