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

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


当前回答

你可以使用文本属性隐藏工具栏按钮:

barButton.enabled = false
barButton.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.clearColor()], forState: .Normal)

也看到我的解决方案与UIBarButtonItem扩展类似的问题:使UIBarButtonItem消失使用快速IOS

其他回答

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

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

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

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

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);
    }
}

这里有一个简单的方法:

hide:  barbuttonItem.width = 0.01;
show:  barbuttonItem.width = 0; //(0 defaults to normal button width, which is the width of the text)

我刚刚在retina iPad上运行了它,0.01太小了,它不会显示出来。

尝试在Swift,不要更新tintColor,如果你有一些设计为你的UIBarButtonItem字体大小在AppDelegate,它将完全改变你的按钮的外观时显示。

在文本按钮的情况下,改变标题可以让你的按钮“消失”。

if WANT_TO_SHOW {
    myBarButtonItem.enabled = true
    myBarButtonItem.title = "BUTTON_NAME"
}else{
    myBarButtonItem.enabled = false
    myBarButtonItem.title = ""
}

这是一个扩展,将处理这一点。

extension UIBarButtonItem {

    var isHidden: Bool {
        get {
            return tintColor == .clear
        }
        set {
            tintColor = newValue ? .clear : .white //or whatever color you want
            isEnabled = !newValue
            isAccessibilityElement = !newValue
        }
    }

}

用法:

myBarButtonItem.isHidden = true