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.
You can use text attributes to hide a bar button:
barButton.enabled = false
barButton.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.clearColor()], forState: .Normal)
Also see my solution with UIBarButtonItem extension for the similar question: Make a UIBarButtonItem disapear using swift IOS
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.
One way to do it is use the initWithCustomView:(UIView *)
property of when allocating the UIBarButtonItem
. Subclass for UIView
will have hide/unhide property.
For example:
1. Have a UIButton
which you want to hide/unhide.
2. Make the UIButton
as the custom view. Like :
UIButton*myButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];//your button
UIBarButtonItem*yourBarButton=[[UIBarButtonItem alloc] initWithCustomView:myButton];
3. You can hide/unhide the myButton
you've created. [myButton setHidden:YES];
For Swift version, here is the code:
For UINavigationBar
:
self.navigationItem.rightBarButtonItem = nil
self.navigationItem.leftBarButtonItem = nil
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.
In case the UIBarButtonItem has an image instead of the text in it you can do this to hide it:
navigationBar.topItem.rightBarButtonItem.customView.alpha = 0.0;