1

Following this question and the documentation example. I tried to implement a piece of code that enable and disable two buttons (Undo and Redo) in a macOS Toolbar.

override func validateToolbarItem(_ toolbarItem: NSToolbarItem) -> Bool {

    var enable = false

    if toolbarItem.itemIdentifier.isEqual("undoButton") {
        enable = (mainTextField.undoManager?.canUndo)!
    }
    else if toolbarItem.itemIdentifier.isEqual("redoButton") {
        enable = (mainTextField.undoManager?.canRedo)!
    }

    return enable
}

Unfortunately it seems that the code has not effect. What am I missing?

Cue
  • 2,952
  • 3
  • 33
  • 54
  • `validateToolbarItem` is called on the target of the toolbar item. Is the toolbar item an image toolbar item or a view/control toolbar item? Documentation: [Validating Toolbar Items](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Toolbars/Tasks/ValidatingTBItems.html). – Willeke Jun 16 '17 at 19:38

1 Answers1

2
    enum toolItems:Int {
        case undo = 0
        case redo = 1
    }

    // creating an array at the beginning (AppleDelegate, windowDidLoad, ...) //
    func makeToolbar() {
        toolbarItemState.insert("1", at: toolItems.undo.rawValue) // 0
        toolbarItemState.insert("0", at: toolItems.redo.rawValue) // 1
    }

    override func validateToolbarItem(_ toolbarItem:NSToolbarItem) -> Bool {
        var enable:Bool = false
        if ((toolbarItemState[toolbarItem.tag] as AnyObject).integerValue == 1) {
            enable = true
        }
        return enable
    }

    func editToolItem(index:Int,state:String) -> Void {
        toolbarItemState.replaceObject(at: index, with: state)
    }

When the application launches, create an array of toolbarItemState. If you want to change the state of the undo toolbar item to 'on,' for example,

editToolItem(index: toolItems.savePict.undo, state: "1")

. Now, the undo toolbar item is one. If you set the state to "0," the button will be disabled.

El Tomato
  • 6,479
  • 6
  • 46
  • 75