2016-04-14 6 views
0

オプションキーが押されたときにNSButtonのテキストを変更したいと思います - OS Xでファイルが検出されたときに、オプションキーが押されているときは、 "Keep Both"を "Merge"にします。修飾キーが押されたときにボタンテキストとアクションをプログラム的に変更する

私の場合は、オプションキーを押したときにテキストを含むボタン、たとえば「削除」を「終了」に変更したいと思います。さらに、コピーダイアログのオプションと同様に、その機能はタイトルに応じて変更する必要があります。

Swiftでこれをプログラムで行うことはできますか?

答えて

2

あなたはaddLocalMonitorForEvents(matching:)を使用してサブスクライブし、オプションキーは次のように押されたかどうかを検出することができます

var optionKeyEventMonitor: Any? // property to store reference to the event monitor 

// Add the event monitor 
optionKeyEventMonitor = NSEvent.addLocalMonitorForEvents(matching: .flagsChanged) { event in 
    if event.modifierFlags.contains(.option) { 
     self.button.title = "copy" 
     self.button.action = #selector(self.copyButtonClicked(_:)) 
    } else { 
     self.button.title = "delete" 
     self.button.action = #selector(self.deleteButtonClicked(_:)) 
    } 
    return event 
} 

@IBAction func copyButtonClicked(_ sender: Any) { 
    Swift.print("Copy button was clicked!") 
} 

@IBAction func deleteButtonClicked(_ sender: Any) { 
    Swift.print("Delete button was clicked!") 
} 

作業が完了したときに、イベント・モニターを削除することを忘れないでください:

deinit { 
    if let eventMonitor = optionKeyEventMonitor { 
     NSEvent.removeMonitor(eventMonitor) 
    } 
} 

したくない場合別のメソッドがオプションのキーの状態に応じて呼び出された場合、代わりにボタンをクリックすると、modifierFlagsを確認することができます:

@IBAction func buttonClicked(sender: NSButton) { 
    if NSEvent.modifierFlags().contains(.option) { 
     print("option pressed") 
    } else { 
     print("option not pressed") 
    } 
} 
-1

スウィフト3コード:

関連する問題