How do I show/hide a UIBarButtonItem?

前端 未结 30 2321
执念已碎
执念已碎 2020-11-28 01:18

I created a toolbar in IB with several buttons. I would like to be able to hide/show one of the buttons depending on the state of the data in the main window.

30条回答
  •  没有蜡笔的小新
    2020-11-28 01:55

    This is long way down the answer list, but just in case somebody wants an easy copy and paste for the swift solution, here it is

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

提交回复
热议问题