Search code examples
iosswiftstoryboarduinavigationbaruibarbuttonitem

Re-instantiate storyboard navigation bar buttons


I have two bar button items set up in storyboard and connected to these outlets:

 @IBOutlet weak var sideMenuButton: UIBarButtonItem!

 @IBOutlet weak var selectButton: UIBarButtonItem!

When select button is pressed, I replace those buttons with two others, like so:

deleteButton = UIBarButtonItem(title: "Delete", style: .plain, target: self, action: #selector(deleteButtonPressed(_:)))      
cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelButtonPressed(_:)))

navigationItem.leftBarButtonItem = cancelButton
navigationItem.rightBarButtonItem = deleteButton

Now, I want to change everything back when cancel button is pressed. I am trying to do it by passing the outlets to barButtonItems:

navigationItem.leftBarButtonItem = sideMenuButton
navigationItem.rightBarButtonItem = selectButton

but this doesn't work and nothing shows up. How can I fix this without having to set up all buttons in code? Is there any way to reset the Navigation Bar or re-instantiate the buttons from storyboard?


Solution

  • Your two outlets are weak. So when you are not using them any more, they become nil. Remove the weak from the outlet declarations and your code should work as expected.