Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I show/hide a UIBarButtonItem?

I created a toolbar in IB with several buttons. I would like to be able to hide/show one of the buttons depending on the state of the data in the main window.

UIBarButtonItem doesn't have a hidden property, and any examples I've found so far for hiding them involve setting nav bar buttons to nil, which I don't think I want to do here because I may need to show the button again (not to mention that, if I connect my button to an IBOutlet, if I set that to nil I'm not sure how I'd get it back).

like image 856
Sasha Avatar asked Oct 22 '22 19:10

Sasha


People also ask

How do I hide UIBarButtonItem in swift 5?

There is no way to "hide" a UIBarButtonItem you must remove it from the superView and add it back when you want to display it again.

How do I hide items in navigation bar?

Go to your Navbar settings and find the navigation item you want to hide for a particular page. Click to edit and assign it a classname. You could assign it something like "hide-navigation-item."


1 Answers

Save your button in a strong outlet (let's call it myButton) and do this to add/remove it:

// Get the reference to the current toolbar buttons
NSMutableArray *toolbarButtons = [self.toolbarItems mutableCopy];

// This is how you remove the button from the toolbar and animate it
[toolbarButtons removeObject:self.myButton];
[self setToolbarItems:toolbarButtons animated:YES];

// This is how you add the button to the toolbar and animate it
if (![toolbarButtons containsObject:self.myButton]) {
    // The following line adds the object to the end of the array.  
    // If you want to add the button somewhere else, use the `insertObject:atIndex:` 
    // method instead of the `addObject` method.
    [toolbarButtons addObject:self.myButton];
    [self setToolbarItems:toolbarButtons animated:YES];
}

Because it is stored in the outlet, you will keep a reference to it even when it isn't on the toolbar.

like image 271
lnafziger Avatar answered Oct 24 '22 08:10

lnafziger