3

I'm trying to show the UISearchController by tapping on the UIBarButtonItem. But the SearchBar appears behind the NavigationBar. If I set definesPresentationContext = false, then the SearchBar appears above the NavigationBar, but the transitions don't work.

    @IBAction func searchButtonPressed(_ sender: Any) {
        searchResultsController = self.storyboard?.instantiateViewController(withIdentifier: "SearchResultsController") as? SearchResultsController
        searchResultsController.tableView.delegate = self
        let searchController = UISearchController(searchResultsController: searchResultsController)
        searchController.searchResultsUpdater = searchResultsController
        searchController.hidesNavigationBarDuringPresentation = false
        searchController.searchBar.autocapitalizationType = .words
        definesPresentationContext = true
        present(searchController, animated: true)
    }

Before BarButtonItem tapped

After BarButtonItem tapped

View UI Hierarchy

Interface Builder

searchController.hidesNavigationBarDuringPresentation = false solve this problem, but I need the navigation bar to not be hidden

UPDATE:

Inserting the SearchBar inside the Navigation Bar is not suitable for my app https://i.sstatic.net/PGegh.jpg

1 Answer 1

1

If you are using UITableViewController then you can do the following:

let searchController = UISearchController(searchResultsController: nil)
searchController.obscuresBackgroundDuringPresentation = false
searchController.definesPresentationContext = true

Then, you need to assign this searchController to navigationItem:

self.navigationItem.searchController = searchController

Now searchbar is going to appear when you pull the tableview and will look this way:

enter image description here

If you want to keep the search bar permanently, then do this:

self.navigationItem.hidesSearchBarWhenScrolling = false
Sign up to request clarification or add additional context in comments.

5 Comments

I need to display the searchbar at front of viewcontroller when the button is tapped like iOS Calendar app
In the situation I described it will get hidden too when you scroll, and appear only if you pull the tableview. Or do you want it to appear on a specific button tap exclusively?
Yes, I want in to appear on button tap
You can assign self.navigationItem.searchController = searchController on your button tap. That will do the job.
Unfortunately, this doesn't work for my app imgur.com/a/74e5sSk

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.