あなたは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")
}
}