使用 Swift 的 MASShortcut 简单回调

Simple Callback with MASShortcut using Swift

我安装了最新的 (2015-02-03) MASShortcut 作为 CocoaPod,并为非常基本的 OS X Swift 应用程序安装了正确的桥接头。我最终得到了以下代码,但我不知道自己做错了什么?:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!

    func callback() {
         NSLog("callback")
    }

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        let keyMask = NSEventModifierFlags.CommandKeyMask | NSEventModifierFlags.AlternateKeyMask
        let shortcut = MASShortcut.shortcutWithKeyCode(kVK_Space, modifierFlags: UInt(keyMask.rawValue))
        MASShortcut.addGlobalHotkeyMonitorWithShortcut(shortcut, handler: callback)
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }


}

提前致谢!

这里有一些问题。在修复它们之前,你应该确保你已经安装了 MASShortcut 2.1.2(你可以在你的 Podfile.lock 中看到它)。如果你不这样做,你应该 运行 pod update 获取最新版本。

你测试这个的另一个潜在问题是你的快捷方式与 OS X 默认快捷方式冲突。在您当前的示例中,Command+Option+Space 必然会打开一个 Finder window 并选择搜索字段。如果您禁用了此功能,那很好,否则我建议将 Control 添加到您的测试用例中。

到目前为止,您的代码存在一些问题。首先,我建议将您的 keyMask 声明稍微更改为:

let keyMask: NSEventModifierFlags = .CommandKeyMask | .ControlKeyMask | .AlternateKeyMask

这样 Swift 可以推断出类型,你只需要 NSEventModifierFlags 一次(注意我在上面的评论中添加了 .ControlKeyMask)。

Swift 中关于枚举的一个很酷的部分是您可以对它们调用 rawValue。在这种情况下,NSEventModifierFlagsrawValue 是一个 UInt,它将在创建快捷方式时解决您的类型问题。

现在你的 keyCode 参数也必须是 UInt。所以你可以把它拉出来变成一个临时值:

let keyCode = UInt(kVK_Space)

在Swift中,看起来像class级初始化器的方法实际上变成了Swift级初始化器。因此,在这种情况下,当 Swift 实际上已将其转换为初始值设定项时,您试图调用名为 shortcutWithKeyCode:modifierFlags: 的 class 方法。所以你可以像这样创建你的快捷方式:

let shortcut = MASShortcut(keyCode: keyCode, modifierFlags: keyMask.rawValue)

注意 rawValue 调用将我们的修饰符标志转换为 UInt

最后,API全局注册这个快捷方式其实是MASShortcutMonitor上的一个方法。在你的桥接 header 中你有:

#import <MASShortcut/MASShortcut.h>

您必须添加新的导入才能获得此 API。新的是:

#import <MASShortcut/MASShortcutMonitor.h>

现在您可以注册您的快捷方式了:

MASShortcutMonitor.sharedMonitor().registerShortcut(shortcut, withAction: callback)

一切准备就绪。您的回调函数已正确设置!

最后一件事。我建议像这样删除 applicationWillTerminate: 中的快捷方式:

MASShortcutMonitor.sharedMonitor().unregisterAllShortcuts()

哇,这是一个很好的答案。太感谢了!我意识到我应该更长时间地研究 Swift 的基础知识。您的解决方案非常有效!

然而,一个小细节是多余的。您不必添加桥接头

#import <MASShortcut/MASShortcutMonitor.h>

如果您按照文档中所示创建桥接头文件。我的桥接头文件包含

#import <Cocoa/Cocoa.h>
#import <MASShortcut/Shortcut.h>

和Shortcut.h已经引用了MASShortcutMonitor.h。

再次:非常感谢!!