我在IB中创建了一个带有几个按钮的工具栏。我想能够隐藏/显示一个按钮取决于数据的状态在主窗口。
UIBarButtonItem没有隐藏属性,到目前为止我发现的任何隐藏它们的例子都涉及将导航栏按钮设置为nil,我不认为我想在这里做,因为我可能需要再次显示按钮(更不用说,如果我连接我的按钮到IBOutlet,如果我设置为nil,我不确定我如何得到它)。
我在IB中创建了一个带有几个按钮的工具栏。我想能够隐藏/显示一个按钮取决于数据的状态在主窗口。
UIBarButtonItem没有隐藏属性,到目前为止我发现的任何隐藏它们的例子都涉及将导航栏按钮设置为nil,我不认为我想在这里做,因为我可能需要再次显示按钮(更不用说,如果我连接我的按钮到IBOutlet,如果我设置为nil,我不确定我如何得到它)。
当前回答
如果UIBarButtonItem有一个图像而不是文本,你可以这样做来隐藏它: navigationBar.topItem.rightBarButtonItem.customView.alpha = 0.0;
其他回答
我在我的项目中使用了IBOutlets。所以我的解决方案是:
@IBOutlet weak var addBarButton: UIBarButtonItem!
addBarButton.enabled = false
addBarButton.tintColor = UIColor.clearColor()
当您需要再次显示此栏时,只需设置反转属性。
在Swift 3中使用isEnable属性。
一种方法是在分配UIBarButtonItem时使用initWithCustomView:(UIView *)属性。UIView的子类有hide/unhide属性。
例如:
1. 有一个你想隐藏/取消隐藏的UIButton。
2. 让uibuttas成为自定义视图。如:
UIButton*myButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];//your button
UIBarButtonItem*yourBarButton=[[UIBarButtonItem alloc] initWithCustomView:myButton];
3.你可以隐藏/取消隐藏你已经创建的myButton。(myButton setHidden:是的);
将你的按钮保存在一个强outlet中(让我们称之为myButton),然后添加/删除它:
// 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];
}
因为它存储在输出中,所以即使它不在工具栏上,您也将保留对它的引用。
我目前正在运行OS X Yosemite开发者预览7和Xcode 6 beta 6,目标是iOS 7.1,以下解决方案对我来说很好:
为uinavigationitem和UIBarButtonItems创建outlet 运行以下代码删除 (自我。navItem setRightBarButtonItem: nil); (自我。navItem setLeftBarButtonItem: nil); 运行以下代码再次添加按钮 (自我。navItem setRightBarButtonItem deleteItem):; (自我。navItem setLeftBarButtonItem addItem):;
补充Eli Burke的回应,如果你的uibarbuttonitem有一个背景图像而不是一个标题,你可以使用代码:
-(void)toggleLogoutButton:(bool)show{
if (show) {
self.tabButton.style = UIBarButtonItemStyleBordered;
self.tabButton.enabled = true;
UIImage* imageMap = [UIImage imageNamed:@"btn_img.png"];
[((UIButton *)[self.tabButton customView]) setBackgroundImage:imageMap forState:UIControlStateNormal];
} else {
self.tabButton.style = UIBarButtonItemStylePlain;
self.tabButton.enabled = false;
[((UIButton *)[self.tabButton customView]) setBackgroundImage:nil forState:UIControlStateNormal];
}
}