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.
self.dismissButton.customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
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 :-
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.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];
I used IBOutlets in my project. So my solution was:
@IBOutlet weak var addBarButton: UIBarButtonItem!
addBarButton.enabled = false
addBarButton.tintColor = UIColor.clearColor()
And when you'll need to show this bar again, just set reversed properties.
In Swift 3 instead enable
use isEnable
property.
If you are using Swift 3
if (ShowCondition){
self.navigationItem.rightBarButtonItem = self.addAsset_btn
}
else {
self.navigationItem.rightBarButtonItem = nil
}
Just Set barButton.customView = UIView()
and see the Trick
This is long way down the answer list, but just in case somebody wants an easy copy and paste for the swift solution, here it is
func hideToolbarItem(button: UIBarButtonItem, withToolbar toolbar: UIToolbar) {
var toolbarButtons: [UIBarButtonItem] = toolbar.items!
toolbarButtons.removeAtIndex(toolbarButtons.indexOf(button)!)
toolbar.setItems(toolbarButtons, animated: true)
}
func showToolbarItem(button: UIBarButtonItem, inToolbar toolbar: UIToolbar, atIndex index: Int) {
var toolbarButtons: [UIBarButtonItem] = toolbar.items!
if !toolbarButtons.contains(button) {
toolbarButtons.insert(button, atIndex: index)
toolbar.setItems(toolbarButtons, animated:true);
}
}