我在IB中创建了一个带有几个按钮的工具栏。我想能够隐藏/显示一个按钮取决于数据的状态在主窗口。
UIBarButtonItem没有隐藏属性,到目前为止我发现的任何隐藏它们的例子都涉及将导航栏按钮设置为nil,我不认为我想在这里做,因为我可能需要再次显示按钮(更不用说,如果我连接我的按钮到IBOutlet,如果我设置为nil,我不确定我如何得到它)。
我在IB中创建了一个带有几个按钮的工具栏。我想能够隐藏/显示一个按钮取决于数据的状态在主窗口。
UIBarButtonItem没有隐藏属性,到目前为止我发现的任何隐藏它们的例子都涉及将导航栏按钮设置为nil,我不认为我想在这里做,因为我可能需要再次显示按钮(更不用说,如果我连接我的按钮到IBOutlet,如果我设置为nil,我不确定我如何得到它)。
当前回答
我有一个问题,我有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
我希望它能帮助到有类似问题的人。
其他回答
只需设置barButton。customView = UIView(),看看窍门
在IB中,如果你让按钮的标题为空,它将不会出现(从未初始化?)我经常在UI更新的开发过程中这样做,如果我想让一个栏按钮项目临时消失,而不删除它并丢弃它的所有出口引用。
这在运行时没有相同的效果,将按钮的标题设置为nil不会导致整个按钮消失。抱歉并不能真正回答你的问题,但可能对一些人有用。
编辑:此技巧仅在按钮的样式设置为普通时有效
我的解是设定边界。宽度为0,你有什么UIBarButtonItem(我使用这种方法与UIButton和UISearchBar):
隐藏:
self.btnXXX.bounds = CGRectMake(0,0,0,0);
显示:
self.btnXXX.bounds = CGRectMake(0,0,40,30); // <-- put your sizes here
我认为我将根据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];
}
}
我将在这里添加我的解决方案,因为我还没有在这里找到它。我有一个动态按钮,其图像取决于一个控件的状态。对我来说,最简单的解决方案是,如果控件不存在,将图像设置为nil。每次控件更新时,图像都会更新,因此,这对我来说是最优的。为了确保我也设置了enabled为NO。
将宽度设置为最小值在iOS 7上不起作用。