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

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


当前回答

我使用xib和UIToolbar。BarButtonItem在xib文件中创建。我为BarButtonItem创建了IBOutlet。我用这段代码来隐藏BarButtonItem

 self.myBarButtonItem.enabled = NO;
 self.myBarButtonItem.title =  nil;

这对我很有帮助。

其他回答

最后,在iOS 16+中,UIBarButtonItem有isHidden属性。

所以,扩展现有的答案,比如

extension UIBarButtonItem {
    func show() {
        if #available(iOS 16.0, *) {
            isHidden = false
        } else {
            isEnabled = true
            tintColor = .white
        }
    }
    
    func hide() {
        if #available(iOS 16.0, *) {
            isHidden = true
        } else {
            isEnabled = false
            tintColor = .clear
        }
    }
}

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

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

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

self.navigationItem.rightBarButton.enabled = NO;

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

这是一个很长的答案列表,但为了防止有人想要一个简单的复制和粘贴的快速解决方案,这里是

func hideToolbarItem(button: UIBarButtonItem, withToolbar toolbar: UIToolbar) {
    var toolbarButtons: [UIBarButtonItem] = toolbar.items!
    toolbarButtons.removeAtIndex(toolbarButtons.indexOf(button)!)
    toolbar.setItems(toolbarButtons, animated: true)
}

func showToolbarItem(button: UIBarButtonItem, inToolbar toolbar: UIToolbar, atIndex index: Int) {
    var toolbarButtons: [UIBarButtonItem] = toolbar.items!
    if !toolbarButtons.contains(button) {
        toolbarButtons.insert(button, atIndex: index)
        toolbar.setItems(toolbarButtons, animated:true);
    }
}

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

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

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

将你的按钮保存在一个强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];
}

因为它存储在输出中,所以即使它不在工具栏上,您也将保留对它的引用。