toast
toast

Reputation: 1980

Hide bar button items swift

How can I hide my left bar button item?

In my storyboard I dragged a Navigation Bar onto my View Controller, then a Bar Button Item. Under certain conditions I want to hide the Bar Button Item.

None of this works:

override func viewDidLoad() {
    self.navigationItem.leftBarButtonItem = nil
    self.navigationItem.leftBarButtonItems = []
    self.navigationItem.setLeftBarButtonItems([], animated: true)
}

Upvotes: 1

Views: 1623

Answers (2)

Sunly
Sunly

Reputation: 330

You can't access to self.navigationItem.leftBarButtonItem because you manually drag navigationBar from storyboard. I would suggest to do the following instead:

  1. add an IBOutlet of BarButtonItem (eg: barButton) that you created in storyboard
  2. barButton.title = ""
  3. barButton.isEnable = false

This will hide your BarButtonItem, and you can simply show it back later.

Upvotes: 1

matt
matt

Reputation: 535121

I dragged a Navigation Bar onto my View Controller

Well, don't! There is a big difference between a navigation controller interface, where you set the navigationItem, and a loosey-goosey navigation bar just sitting there in the interface, which is what you have.

Embed your view controller in a UINavigationController and do things the right way. Then setting your navigationItem and its properties will work as expected.

Upvotes: 4

Related Questions