我在IB中创建了一个带有几个按钮的工具栏。我想能够隐藏/显示一个按钮取决于数据的状态在主窗口。
UIBarButtonItem没有隐藏属性,到目前为止我发现的任何隐藏它们的例子都涉及将导航栏按钮设置为nil,我不认为我想在这里做,因为我可能需要再次显示按钮(更不用说,如果我连接我的按钮到IBOutlet,如果我设置为nil,我不确定我如何得到它)。
我在IB中创建了一个带有几个按钮的工具栏。我想能够隐藏/显示一个按钮取决于数据的状态在主窗口。
UIBarButtonItem没有隐藏属性,到目前为止我发现的任何隐藏它们的例子都涉及将导航栏按钮设置为nil,我不认为我想在这里做,因为我可能需要再次显示按钮(更不用说,如果我连接我的按钮到IBOutlet,如果我设置为nil,我不确定我如何得到它)。
当前回答
下面是我的解决方案,虽然我正在寻找它的导航栏。
navBar.topItem.rightBarButtonItem = nil;
这里“navBar”是XIB视图中NavigationBar的IBOutlet 在这里,我想隐藏按钮或根据某些条件显示它。所以我在“如果”测试条件,如果是真的,我将按钮设置为nil在viewDidLoad方法的目标视图。
这可能与你的问题不相关,但如果你想隐藏导航栏上的按钮,情况类似
其他回答
将你的按钮保存在一个强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];
}
因为它存储在输出中,所以即使它不在工具栏上,您也将保留对它的引用。
没有办法“隐藏”一个UIBarButtonItem,你必须从superView中删除它,当你想再次显示它时再添加它。
iOS 8。带有自定义图像的UIBarButtonItem。 我试过很多方法,但大多数都没用。 Max的解决方案,thesetTintColor没有改变为任何颜色。 这是我自己想出来的,我想它会对别人有用。
隐藏:
[self.navigationItem.rightBarButtonItem setEnabled:NO];
[self.navigationItem.rightBarButtonItem setImage:nil];
显示:
[self.navigationItem.rightBarButtonItem setEnabled:YES];
[self.navigationItem.rightBarButtonItem setImage:image];
我认为我将根据lnafziger接受的答案分享一些帮助方法,因为我在每个工具栏中都有多个按钮:
-(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];
}
}
只需设置barButton。customView = UIView(),看看窍门