luke luke - 4 months ago 14
Swift Question

Hide Nav bar items during search

I have 3 nav bar items in my nav bar like so:

func setupNavBarButtons() {
let searchImage = UIImage(named: "search_icon")?.imageWithRenderingMode(.AlwaysOriginal)
let searchBarButtonItem = UIBarButtonItem(image: searchImage, style: .Plain, target: self, action: #selector(handleSearch))

let mapBarButtonItem = UIBarButtonItem(title: "Map", style: .Plain, target: self, action: #selector(displayMap))
navigationItem.rightBarButtonItems = [mapBarButtonItem , searchBarButtonItem]


let filterBarButtonItem = UIBarButtonItem(title: "Filter", style: .Plain , target: self, action: #selector(displayFilter))
navigationItem.leftBarButtonItem = filterBarButtonItem
}


When I tap the search icon it calls the function below:

func handleSearch() {
self.navigationItem.titleView = searchController.searchBar

}


I want to hide all nav bar items while user is searching and then return nav bar items once user is done searching

Answer

You can try like this in your handleSearch method remove the left and right bar button item, After that on searchBarCancelButtonClicked method of UISearchBarDelegate you can set it again that bar items.

func handleSearch() {
    searchController.searchBar.hidden = false
    self.navigationItem.titleView = searchController.searchBar
    searchController.searchBar.becomeFirstResponder()
    navigationItem.rightBarButtonItems = nil
    navigationItem.leftBarButtonItems = nil
}

func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    self.setupNavBarButtons()
    searchController.searchBar.hidden = true
}