Show/Hide barButtonItem [duplicate]

I'm trying to show/hide a UIBarButtonItem. I added a barButton to the right side in the storyboard. Then in viewDidLoad, I made the rightBarButtonItem to nil. Later on, I set it to the button I added in the storyboard. Here's my code:

// Right barButtonItem added in storybord:
@IBOutlet weak var deleteBarButton: UIBarButtonItem! 

// viewDidLoad
self.navigationItem.rightBarButtonItem = nil

// Later on...
self.navigationItem.rightBarButtonItem = self.deleteBarButton

When I set self.deleteBarButton to the rightBarButtonItem, nothing happens. It doesn't show it. What am I doing wrong, and what's the correct/most efficient way to show/hide a barButtonItem?

Update

I tried the following:

self.deleteBarButton.hidden = true

But I get the following error:

UIBarButtonItem does not have a member named 'hidden'


Solution 1:

Just got the answer! All you have to do is create a strong IBOutlet, then you can do the following:

// viewDidLoad
self.navigationItem.rightBarButtonItem = nil

// Later on...
self.navigationItem.rightBarButtonItem = self.deleteBarButton

Solution 2:

Update 2

You could just set the button's text to nothing:

self.deleteBarButton.title = "";

Update 1

I would use the enabled property to illuminate the button as follows (although it does not completely make the button invisible, it allows the user to know it will not perform an action).

This can act as a variable to let you know that the button is hidden in your case:

Illuminated: (place in ViewDidLoad)

self.deleteBarButton.enabled = true;

Darkened: (place later on)

self.deleteBarButton.enabled = false;

Then I would add the following to make it completely disappear:

self.navigationController?.navigationItem.rightBarButtonItem?.tintColor = UIColor.clearColor();