h4labs
h4labs

Reputation: 785

iOS11 SearchController in NavigationBar with Scope Buttons

enter image description here

In iOS 11 you can put a UISearchController in the NavigationBar with a few lines of code.

I set up everything in the ViewController.swift.

func setupNavBar() {
    navigationController?.navigationBar.prefersLargeTitles = true

    let searchController = UISearchController(searchResultsController: nil)
    searchController.searchResultsUpdater = wordViewController
    searchController.searchBar.scopeButtonTitles = ["French", "English"]
    searchController.searchBar.delegate = wordViewController

    navigationItem.searchController = searchController
    // Make searchbar persistent
    navigationItem.hidesSearchBarWhenScrolling = false
}

In my delegate, the search fires and filters properly. However, if I click either of the scope buttons, they simply disappear. This delegate method is never called. (filter by scope is not actually implemented yet)

extension WordViewController: UISearchBarDelegate {

 func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {

    if let searchText = searchBar.text {
        print("Scoped changed: \(searchText)")
        filteredWordList = wordList.filter({$0.contains(searchText)})
    }
  }
}

Full source is on Github:

https://github.com/melling/ios_topics/tree/master/NavBarSearch https://github.com/melling/ios_topics/tree/master/NavBarSearch/NavBarSearch

Upvotes: 5

Views: 2600

Answers (3)

WeichengChu
WeichengChu

Reputation: 116

In your ViewController, you need to add this line

self.definesPresentationContext = YES;

This tells the UISearchController the presentation context it needs to use, which is defined by your ViewController.

Check this link for more details: http://asciiwwdc.com/2014/sessions/228

Upvotes: 0

BananaNeil
BananaNeil

Reputation: 10762

I was able to use Artem's solution,

searchController.dimsBackgroundDuringPresentation = false

but I then ran into the problem of no longer being able to click on the background to dismiss the focus on the search bar.

To resolve this, I created my own dimmer uiview (screen size, background color of black with 25% opacity), and added that to the view of the currently presented screen, and listened for a tap. When the user taps it, I fade it out and set

searchController.active = false

Upvotes: 0

Artem  Demchenko
Artem Demchenko

Reputation: 946

Try to add this code within setupNavBar():

searchController.dimsBackgroundDuringPresentation = false

Upvotes: 1

Related Questions