Jessica Jessica - 4 months ago 45
Swift Question

Show/Hide barButtonItem

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

You can store a copy of the leftBarButtonItem in a strong property and set it back when you want.

var leftBarButtonItem : UIBarButtonItem!

Inside viewDidLoad

self.leftBarButtonItem = UIBarButtonItem(title: "test", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)

//shows it
self.navigationItem.leftBarButtonItem = self.leftBarButtonItem

//hides it
self.navigationItem.leftBarButtonItem = nil