Tarvo Mäesepp Tarvo Mäesepp - 3 months ago 32
Swift Question

Hiding searchbar hides navigation bar title also

I have

navigation bar
with
search
button. On the click on it it shows the
searchbar
and on cancel button click it hides. But for some reason if
searchbar
is hidden then the navigation bar titleview hides too. What could cause this? At first I actually wanted it to slide in from right to
titleView
but I couldn't achieve it so I made it like this.

This is the code to show it and to hide it:

//Create searchbar
func createSearchBar(){

searchBar.showsCancelButton = true
searchBar.tintColor = UIColor(red:0.184, green:0.996, blue:0.855, alpha:1.00)
searchBar.placeholder = "Search brands"
searchBar.delegate = self



searchBar.hidden = false
searchBar.alpha = 0

navigationItem.titleView = searchBar
navigationItem.setLeftBarButtonItem(menuButton, animated: true)
navigationItem.setRightBarButtonItem(searchButtton, animated: true)


UIView.animateWithDuration(0.5, animations: {
self.searchBar.alpha = 1
}, completion: { finished in
self.searchBar.becomeFirstResponder()
})


}

//Searchbar hide
func hideSearchBar() {


navigationItem.setLeftBarButtonItem(menuButton, animated: true)
navigationItem.setRightBarButtonItem(searchButtton, animated: true)
searchBar.alpha = 0
UIView.animateWithDuration(1, animations: {


}, completion: { finished in

})
}

//Searchbar cancel button
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
hideSearchBar()
searchBar.endEditing(true)
snusBrandsTableView.reloadData()
}

Answer

If you want set title of navigationItem on hiding of searchBar you need to set the titleView to nil and then set title.

func hideSearchBar() {
    navigationItem.setLeftBarButtonItem(menuButton, animated: true)
    navigationItem.setRightBarButtonItem(searchButtton, animated: true)
    searchBar.alpha = 0
    self.navigationItem.titleView = nil
    self.navigationItem.title = "YourTitle"
}
Comments