问题
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