50

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'

Jessica
  • 9,379
  • 14
  • 65
  • 136

3 Answers3

94

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
Jessica
  • 9,379
  • 14
  • 65
  • 136
29

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();
Jake Chasan
  • 6,290
  • 9
  • 44
  • 90
7

Try to create your barButton manually in viewDidLoad and then show/hide your button.

Code:

var barButton: UIBarButtonItem!

func viewDidLoad() {
    super.viewDidLoad()
    barButton = UIBarButtonItem(title: "Title", style: .Plain, target: self, action: Selector("target_function"))
    self.navigationItem.rightBarButtonItem = barButton
}

func someFunction() {
    self.navigationItem.rightBarButtonItem = nil
    // or
    self.navigationItem.rightBarButtonItem = barButton
}
mkz
  • 2,302
  • 2
  • 30
  • 43
  • For those using a UINavigationBar by itself (not the controller version), you can add a weak IBOutlet reference and then set the right/left bar button items like so (notice the topItem? - I am using navigationBar as my reference name), where barButton is either an IBOutlet reference, or as @mks defined: navigationBar.topItem?.setLeftBarButton(barButton, animated: true) – AlienFromCA Jan 28 '19 at 19:03