2017-06-16 58 views
0

以下this questiondocumentation示例。我试图实现一段代码,在macOS工具栏中启用和禁用两个按钮(撤消和重做)。如何实现validateToolbarItem(_ :)?

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 
} 

不幸的是,似乎代码没有效果。我错过了什么?

+0

在工具栏项目的目标上调用'validateToolbarItem'。工具栏项是图像工具栏项还是视图/控制工具栏项?文档:[验证工具栏项目](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Toolbars/Tasks/ValidatingTBItems.html)。 – Willeke

回答

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

当应用程序启动时,创建toolbarItemState的阵列。例如,如果要将撤消工具栏项目的状态更改为“打开”,例如,

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

。现在,撤消工具栏项目是一个。如果您将状态设置为“0”,该按钮将被禁用。

+0

谢谢El番茄! – Cue