Show/Hide barButtonItem

Jessica picture Jessica · Sep 13, 2015 · Viewed 46.6k times · Source

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'

Answer

Jessica picture Jessica · Sep 13, 2015

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