使用Swift进行MASShortcut的简单回调

时间:2015-02-03 00:18:36

标签: macos swift cocoapods

我安装了最新的(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
    }


}

提前致谢!

2 个答案:

答案 0 :(得分:5)

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

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

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

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

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

关于Swift中枚举的一个很酷的部分是你可以在它们上面调用rawValue。在这种情况下,rawValue的{​​{1}}是NSEventModifierFlags,可以在创建快捷方式时修复您的类型问题。

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

UInt

在Swift中,看起来像类级别初始化器的方法实际上是转入Swift初始化器。因此,在这种情况下,当Swift实际上将其转换为初始化程序时,您尝试调用名为let keyCode = UInt(kVK_Space) 的类方法。因此,您可以像这样创建快捷方式:

shortcutWithKeyCode:modifierFlags:

请注意let shortcut = MASShortcut(keyCode: keyCode, modifierFlags: keyMask.rawValue) 调用将我们的修饰符标记转换为rawValue

最后,全局注册此快捷方式的API实际上是UInt上的方法。在您的桥接标题中:

MASShortcutMonitor

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

#import <MASShortcut/MASShortcut.h>

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

#import <MASShortcut/MASShortcutMonitor.h>

你的一切。您的回调函数已正确设置!

最后一件事。我建议您删除MASShortcutMonitor.sharedMonitor().registerShortcut(shortcut, withAction: callback) 中的快捷方式,如下所示:

applicationWillTerminate:

答案 1 :(得分:-1)

哇,这是一个很好的答案。非常感谢!我意识到我应该更长时间地学习Swift的基础知识。您的解决方案完美无缺!

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

#import <MASShortcut/MASShortcutMonitor.h>

如果您创建桥接头文件,就像文档中所示。我的桥接头文件包含

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

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

再次:非常感谢!!