How to set SearchBar to be active after navigating back from another view controller in iOS

1.1k views Asked by At

How to set SearchBar to be active after navigating back from another view controller?

Type the search string and click search button on search suggestion page, then this page popped by navigation controller. The search result page which was navigated back has a search bar with search text, and refresh the result table view.

But this SearchBar's cancel button is inactive, the first click make search bar become editing mode and the second click just can make it work.

How to set SearchBar's cancel button to be active, so I only need to click cancel button once.

Search suggestion page, will be popped

Search result page, cancel button, two states: active and inactive

1

There are 1 answers

1
nicksweet On

If you're just trying to activate the search bar when it's parent view appears, then you can just add the following to the view controller that contains it:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    if searchBar.canBecomeFirstResponder {
        searchBar.becomeFirstResponder()
    }
}