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

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


当前回答

当栏按钮项被禁用时,将文本颜色设置为透明颜色可能是一个更干净的选项。你不需要在评论中解释什么奇怪的事情。此外,您不会破坏按钮,因此您仍然保留任何相关的故事板segue。

[self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor clearColor]}
                                                      forState:UIControlStateDisabled];

然后当你想隐藏栏按钮项时,你可以这样做:

self.navigationItem.rightBarButton.enabled = NO;

虽然没有隐藏属性,但结果是一样的。

其他回答

如果你使用的是Swift 3

if (ShowCondition){
   self.navigationItem.rightBarButtonItem = self.addAsset_btn 
 } 
else {
   self.navigationItem.rightBarButtonItem = nil
 }

我在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

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

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

在IB中,如果你让按钮的标题为空,它将不会出现(从未初始化?)我经常在UI更新的开发过程中这样做,如果我想让一个栏按钮项目临时消失,而不删除它并丢弃它的所有出口引用。

这在运行时没有相同的效果,将按钮的标题设置为nil不会导致整个按钮消失。抱歉并不能真正回答你的问题,但可能对一些人有用。

编辑:此技巧仅在按钮的样式设置为普通时有效

来自@lnafziger的回答

将你的Barbuttons保存在一个强大的outlet中,并这样隐藏/显示它:

-(void) hideBarButtonItem :(UIBarButtonItem *)myButton {
    // Get the reference to the current toolbar buttons
    NSMutableArray *navBarBtns = [self.navigationItem.rightBarButtonItems mutableCopy];

    // This is how you remove the button from the toolbar and animate it
    [navBarBtns removeObject:myButton];
    [self.navigationItem setRightBarButtonItems:navBarBtns animated:YES];
}


-(void) showBarButtonItem :(UIBarButtonItem *)myButton {
    // Get the reference to the current toolbar buttons
    NSMutableArray *navBarBtns = [self.navigationItem.rightBarButtonItems mutableCopy];

    // This is how you add the button to the toolbar and animate it
    if (![navBarBtns containsObject:myButton]) {
        [navBarBtns addObject:myButton];
        [self.navigationItem setRightBarButtonItems:navBarBtns animated:YES];
    }
}

当需要使用以下功能..

[self showBarButtonItem:self.rightBarBtn1];
[self hideBarButtonItem:self.rightBarBtn1];