I am having trouble implementing MASShortcut (docs here) in a Swift OSX project to listen for global hotkeys. I have managed to import the framework via CocoaPods, and I have a working MASShortcutView instance:
@IBOutlet weak var testShortcutView:MASShortcutView!
I also figured out how to monitor and trigger something with the shortcut (please tell me if this is correct):
let shortcut = MASShortcut(keyCode: keycode, modifierFlags: modifierkeys)
MASShortcutMonitor.sharedMonitor().registerShortcut(shortcut, withAction: callback)
The question here is, how can I get the keyCode and modifierFlags from my MASShortcutView?
I really thank you in advance, I searched everywhere and I can't find an example on how to do this on swift. All I can find is is objective-c, and I can't figure it out.
Following code will register shortcut handler for Cmd+Shift+K key combination
let shortcut = MASShortcut.init(keyCode: UInt(kVK_ANSI_K), modifierFlags: UInt(NSEventModifierFlags.CommandKeyMask.rawValue + NSEventModifierFlags.ShiftKeyMask.rawValue))
MASShortcutMonitor.sharedMonitor().registerShortcut(shortcut, withAction: {
print("Hello world")
})
Cmd and Shift - modifing keys. You should set them in the modifierFlags parameters. Full list of possible values is available in NSEventModifierFlags enum.
For your convenience I have placed sample project on github:
https://github.com/melifaro-/ShortCutSwiftSample
That handles shortcuts changes:
shortcutView.shortcutValueChange = { (sender) in
let callback: (() -> Void)!
if self.shortcutView.shortcutValue.keyCodeStringForKeyEquivalent == "k" {
callback = {
print("K shortcut handler")
}
} else {
callback = {
print("Default handler")
}
}
MASShortcutMonitor.sharedMonitor().registerShortcut(self.shortcutView.shortcutValue, withAction: callback)
}
I have pushed changes into the repo. I would recommend to try following scenario:
Using the shortcut view:
Set Cmd+Shift+K shortcut
Set Cmd+Shift+J shortcut
Try this shortcuts - different callbacks should be performed
Hope it helps.