我在IB中创建了一个带有几个按钮的工具栏。我想能够隐藏/显示一个按钮取决于数据的状态在主窗口。
UIBarButtonItem没有隐藏属性,到目前为止我发现的任何隐藏它们的例子都涉及将导航栏按钮设置为nil,我不认为我想在这里做,因为我可能需要再次显示按钮(更不用说,如果我连接我的按钮到IBOutlet,如果我设置为nil,我不确定我如何得到它)。
我在IB中创建了一个带有几个按钮的工具栏。我想能够隐藏/显示一个按钮取决于数据的状态在主窗口。
UIBarButtonItem没有隐藏属性,到目前为止我发现的任何隐藏它们的例子都涉及将导航栏按钮设置为nil,我不认为我想在这里做,因为我可能需要再次显示按钮(更不用说,如果我连接我的按钮到IBOutlet,如果我设置为nil,我不确定我如何得到它)。
当前回答
只需设置barButton。customView = UIView(),看看窍门
其他回答
下面是我的解决方案,虽然我正在寻找它的导航栏。
navBar.topItem.rightBarButtonItem = nil;
这里“navBar”是XIB视图中NavigationBar的IBOutlet 在这里,我想隐藏按钮或根据某些条件显示它。所以我在“如果”测试条件,如果是真的,我将按钮设置为nil在viewDidLoad方法的目标视图。
这可能与你的问题不相关,但如果你想隐藏导航栏上的按钮,情况类似
我有一个问题,我有2 leftBarButtonItems。在Mac Catalyst上,firstButton指向一个不支持的操作:用AVFoundation录制视频。Mac Catalyst上只有第二个按钮有效:使用UIImagePickerController。
所以在Mac Catalyst上,我必须将第一个UIBarButtonItem指向secondButton,并始终隐藏第二个UIBarButtonItem。在iOS上,两个按钮都应该显示出来。这就是我的解决方案:
#if TARGET_OS_MACCATALYST
self.navigationItem.leftBarButtonItem = self.secondButton;
NSUInteger count = [self.navigationItem.leftBarButtonItems count];
for (NSUInteger i = 0; i < count; i++) {
UIBarButtonItem *thisButton = [self.navigationItem.leftBarButtonItems objectAtIndex:i];
if (i == 1) {
thisButton.enabled = NO;
thisButton.tintColor = [UIColor clearColor];
}
}
#else
self.navigationItem.leftBarButtonItem = self.firstButton;
#endif
我希望它能帮助到有类似问题的人。
一种方法是在分配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:是的);
我的答案是斯威夫特!
if $0 {
self.navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: self.button1)]
} else {
self.navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: self.button2)]
}
将你的按钮保存在一个强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];
}
因为它存储在输出中,所以即使它不在工具栏上,您也将保留对它的引用。