Search code examples
swiftnullpopuprightbarbuttonitemnavigationitem

How can I reset navigation bar items when coming back from popup?


I have a navigation bar with two buttons as the right bar button items and a text field in the title view. If I tap the text field, a search screen pops up and I can enter texts into the text field. The texts in the text field would set the "resultText" variable in my code below. The button items, including filterItem and mapItem, are well connected with @IBOutlet.

I would like to hide the right bar button items when the text field is not empty. With the code shown below, it works fine initially when I enter texts into the text field. However, when I delete the texts in the text field and then returns from the pop-up, the app crashes because the button items are found nil. I do not understand why it is nil. Am I missing something here?

if !resultText.isEmpty {
        navigationItem.rightBarButtonItem = nil
    } else {
        navigationItem.setRightBarButtonItems([filterItem, mapItem], animated: false)     
}

Solution

  • You are adding and removing buttons from the navigation bar, it must be removing reference from view. Try adding it using code -

        func addBarButtonItems() {
            let filterItemBarButton = UIBarButtonItem(title: "filterItem", style: .plain, target: self, action: #selector(filterItemTapped))
            let mapItemBarButton = UIBarButtonItem(title: "mapItem", style: .plain, target: self, action: #selector(mapItemTapped))
            navigationItem.rightBarButtonItems = [filterItemTapped, mapItemTapped]
        }
    
        func removeBarButtonItems() {
            navigationItem.rightBarButtonItems = nil
        }
        
        @objc private func filterItemTapped() {
          //code
        }
        
        @objc private func mapItemTapped() {
          //code
        }
    

    Call these methods correctly in textField delegate methods.