我在IB中创建了一个带有几个按钮的工具栏。我想能够隐藏/显示一个按钮取决于数据的状态在主窗口。

UIBarButtonItem没有隐藏属性,到目前为止我发现的任何隐藏它们的例子都涉及将导航栏按钮设置为nil,我不认为我想在这里做,因为我可能需要再次显示按钮(更不用说,如果我连接我的按钮到IBOutlet,如果我设置为nil,我不确定我如何得到它)。


当前回答

归功于@lnafziger、@MindSpiker、@vishal等。都

我为单个右(或左)栏按钮设计的最简单的一行代码是:

self.navigationItem.rightBarButtonItem = <#StateExpression#>
    ? <#StrongPropertyButton#> : nil;

如:

@interface MyClass()

@property (strong, nonatomic) IBOutlet UIBarButtonItem *<#StrongPropertyButton#>;

@end

@implementation

- (void) updateState
{
    self.navigationItem.rightBarButtonItem = <#StateExpression#>
        ? <#StrongPropertyButton#> : nil;
}

@end

我测试了这个,它为我工作(与强栏按钮项目有线通过IB)。

其他回答

我认为我将根据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];
    }
}

一种方法是在分配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:是的);

没有办法“隐藏”一个UIBarButtonItem,你必须从superView中删除它,当你想再次显示它时再添加它。

对于Swift 3和Swift 4,你可以这样做来隐藏UIBarButtomItem:

self.deleteButton.isEnabled = false
self.deleteButton.tintColor = UIColor.clear

为了显示UIBarButtonItem:

self.deleteButton.isEnabled = true
self.deleteButton.tintColor = UIColor.blue

在tintColor上,你必须指定UIBarButtomItem使用的原始颜色

我在Max和其他人建议的tintColor和isEnabled方法中发现了另一个问题——当VoiceOver为可访问性启用时,按钮在逻辑上是隐藏的,可访问性光标仍然会集中在栏按钮上,并声明它是“变暗”的(即因为isEnabled设置为false)。在公认的答案中,这种方法不会受到这种副作用的影响,但我发现的另一种方法是在“隐藏”按钮时将isAccessibilityElement设置为false:

deleteButton.tintColor = UIColor.clear
deleteButton.isEnabled = false
deleteButton.isAccessibilityElement = false

然后在“显示”按钮时将isAccessibilityElement设置为true:

deleteButton.tintColor = UIColor.blue
deleteButton.isEnabled = true
deleteButton.isAccessibilityElement = true

在我的例子中,栏按钮项仍然占据空间不是问题,因为我们隐藏/显示了右栏按钮项的最左侧。