在Swift项目上快速使用MASShortcut框架

wav*_*ves 2 macos xcode cocoa macos-carbon swift

我在Swift OSX项目中实现MASShortcut(此处的文档)以侦听全局热键时遇到问题.我已经设法通过CocoaPods导入框架,我有一个工作的MASShortcutView实例:

@IBOutlet weak var testShortcutView:MASShortcutView!
Run Code Online (Sandbox Code Playgroud)

我还想出了如何使用快捷方式监视和触发某些内容(请告诉我这是否正确):

let shortcut = MASShortcut(keyCode: keycode, modifierFlags: modifierkeys)

MASShortcutMonitor.sharedMonitor().registerShortcut(shortcut, withAction: callback)
Run Code Online (Sandbox Code Playgroud)

这里的问题是,如何从MASShortcutView获取keyCode和modifierFlags?


我真的非常感谢你,我到处搜索,我找不到一个如何在swift上做这个的例子.我所能找到的只是客观的,我无法弄明白.

Igo*_* B. 10

下面的代码将为Cmd + Shift + K组合键注册快捷键处理程序

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")
})
Run Code Online (Sandbox Code Playgroud)

Cmd和Shift - 修改键.您应该在modifierFlags参数中设置它们.NSEventModifierFlags枚举中提供了可能值的完整列表.

为方便起见,我在github上放置了示例项目:

https://github.com/melifaro-/ShortCutSwiftSample

处理快捷方式更改:

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)
}
Run Code Online (Sandbox Code Playgroud)

我已将更改推送到回购.我建议尝试以下方案:

使用快捷方式视图:

  1. 设置Cmd + Shift + K快捷键

  2. 设置Cmd + Shift + J快捷键

  3. 尝试这个快捷方式 - 应该执行不同的回调

希望能帮助到你.