How to implement validateToolbarItem(_:)?

守給你的承諾、 提交于 2019-12-11 07:36:55

问题


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?


回答1:


    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.



来源:https://stackoverflow.com/questions/44596480/how-to-implement-validatetoolbaritem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!