Search code examples
swiftnavigationhidetitlesearchbar

How to put self.navigationItem.titleView with title after replace it with searchbar in swift


I have searchbar , when click image, it will create searchbar at top navigation , replace with title. Then when tap outside searchbar , the title don't show again , it still with searchbar (textfield), how to show again title if tap or click outside from searchbar ?

this is code to create searchBar at top navigation , replace with title.

func createSearchBar(){
    searchBar.sizeToFit()
    searchBar.showsCancelButton = false
    searchBar.placeholder = "Enter key"
    searchBar.delegate = self
    self.navigationItem.titleView = searchBar
}

This is code when tap outside searchbar

extension ViewCon {
func hideKeyboardWhenTappedAround() {
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewCon.dismissKeyboard))
    view.addGestureRecognizer(tap)
}

func dismissKeyboard() {
    self.searchBar.resignFirstResponder()
 self.navigationController?.navigationBar.topItem?.title="Title List"
}

}

But how i want show title on top navigation again ?


Solution

  • you need to set the to nil

    self.navigationItem.titleView = nil
    

    see: https://developer.apple.com/reference/uikit/uinavigationitem/1624935-titleview