2017-06-16 10 views
0

this questionおよびdocumentationの例に従う。私は、macOSツールバーで2つのボタン(元に戻す、やり直す)を有効/無効にするコードを実装しようとしました。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") 

「」上にアンドゥツールバー項目の状態を変更する場合。今、ツールバーの取り消し項目は1です。状態を「0」に設定すると、ボタンは無効になります。

+0

ありがとうエルトマト! – Cue

関連する問題