How do I show/hide a UIBarButtonItem?
Solution 1:
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.
Solution 2:
I know this answer is late for this question. However, it might help if anybody else faces a similar situation.
In iOS 7, to hide a bar button item, we can use the following two techniques :-
- use
SetTitleTextAttributes
:- This works great on bar button items like "Done", "Save" etc. However, it does not work on items like Add, Trash symbol etc.(atleast not for me) since they are not texts. - use
TintColor
:- If I have a bar button item called "deleteButton" :-
To hide the button, I used the following code:-
[self.deleteButton setEnabled:NO];
[self.deleteButton setTintColor: [UIColor clearColor]];
To show the button again I used the following code:-
[self.deleteButton setEnabled:YES];
[self.deleteButton setTintColor:nil];
Solution 3:
Here's a simple approach:
hide: barbuttonItem.width = 0.01;
show: barbuttonItem.width = 0; //(0 defaults to normal button width, which is the width of the text)
I just ran it on my retina iPad, and .01 is small enough for it to not show up.
Solution 4:
It is possible to hide a button in place without changing its width or removing it from the bar. If you set the style to plain, remove the title, and disable the button, it will disappear. To restore it, just reverse your changes.
-(void)toggleBarButton:(bool)show
{
if (show) {
btn.style = UIBarButtonItemStyleBordered;
btn.enabled = true;
btn.title = @"MyTitle";
} else {
btn.style = UIBarButtonItemStylePlain;
btn.enabled = false;
btn.title = nil;
}
}