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.
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.
Some helper methods I thought I'd share based upon lnafziger's accepted answer as I have multiple toolbars and multiple buttons in each:
-(void) hideToolbarItem:(UIBarButtonItem*) button inToolbar:(UIToolbar*) toolbar{
NSMutableArray *toolbarButtons = [toolbar.items mutableCopy];
[toolbarButtons removeObject:button];
[toolbar setItems:toolbarButtons animated:NO];
}
-(void) showToolbarItem:(UIBarButtonItem*) button inToolbar:(UIToolbar*) toolbar atIndex:(int) index{
NSMutableArray *toolbarButtons = [toolbar.items mutableCopy];
if (![toolbarButtons containsObject:button]){
[toolbarButtons insertObject:button atIndex:index];
[self setToolbarItems:toolbarButtons animated:YES];
}
}
You can easily get the view and hide it this way
let view: UIView = barButtonItem.valueForKey("view") as! UIView
view.hidden = true
I am currently running OS X Yosemite Developer Preview 7 and Xcode 6 beta 6 targeting iOS 7.1 and following solution works fine for me:
UINavigationItem
and UIBarButtonItem
sRun following code to remove
[self.navItem setRightBarButtonItem:nil];
[self.navItem setLeftBarButtonItem:nil];
Run following codes to add buttons again
[self.navItem setRightBarButtonItem:deleteItem];
[self.navItem setLeftBarButtonItem:addItem];
@IBDesignable class AttributedBarButtonItem: UIBarButtonItem {
var isHidden: Bool = false {
didSet {
isEnabled = !isHidden
tintColor = isHidden ? UIColor.clear : UIColor.black
}
}
}
And now simply change isHidden
property.
Improving From @lnafziger answer
Save your Barbuttons in a strong outlet and do this to hide/show it:
-(void) hideBarButtonItem :(UIBarButtonItem *)myButton {
// Get the reference to the current toolbar buttons
NSMutableArray *navBarBtns = [self.navigationItem.rightBarButtonItems mutableCopy];
// This is how you remove the button from the toolbar and animate it
[navBarBtns removeObject:myButton];
[self.navigationItem setRightBarButtonItems:navBarBtns animated:YES];
}
-(void) showBarButtonItem :(UIBarButtonItem *)myButton {
// Get the reference to the current toolbar buttons
NSMutableArray *navBarBtns = [self.navigationItem.rightBarButtonItems mutableCopy];
// This is how you add the button to the toolbar and animate it
if (![navBarBtns containsObject:myButton]) {
[navBarBtns addObject:myButton];
[self.navigationItem setRightBarButtonItems:navBarBtns animated:YES];
}
}
When ever required use below Function..
[self showBarButtonItem:self.rightBarBtn1];
[self hideBarButtonItem:self.rightBarBtn1];