iosuibarbuttonitemuitoolbar

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).


Solution

  • 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.