我正在尝试使用HotKey实现快捷键"Command + Option + J“,但由于某些原因,它在视图控制器之外无法工作。这个应用程序是以菜单栏下拉的形式实现的,所以没有一个实际的窗口可以放在前面。我期待着我的消息被打印出来。我有两个按钮,注册和取消注册,当我注册并打印出组合键时,我看到它已经注册了,所以我相信它是有效的。不幸的是,当我在另一个窗口打开或在桌面视图上按组合键时,没有打印任何注释。任何帮助都是非常感谢的。
//
// ViewController.swift
//
import Cocoa
import AppKit
import HotKey
import Carbon
class ViewController: NSViewController {
@IBOutlet var pressedLabel: NSTextField!
private var hotKey: HotKey? {
didSet {
guard let hotKey = hotKey else {
pressedLabel.stringValue = "Unregistered"
return
}
pressedLabel.stringValue = "Registered"
hotKey.keyDownHandler = { [weak self] in
NSApplication.shared.orderedWindows.forEach({ (window) in
print("woo")
})
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
register(self)
// Do any additional setup after loading the view.
}
@IBAction func unregister(_ sender: Any?) {
hotKey = nil
print("the hot key is ", hotKey?.keyCombo)
}
@IBAction func register(_ sender: Any) {
hotKey = HotKey(keyCombo: KeyCombo(key: .j, modifiers: [.command, .shift])
)
}
}发布于 2020-09-22 17:52:35
这可能是一个引用问题
private var hotKey: HotKey?HotKey配置旨在保持活动状态。它处理全局按键事件,然后调用回调。如果您将其放入视图控制器中,然后从屏幕中移除视图控制器的窗口,或者以其他方式将其解除分配,那么它的私有HotKey引用也会消失,从而有效地销毁事件处理程序。
要尝试这种情况,可以将hotKey属性移动到AppDelegate。那么属性引用将是长期的(确切地说,直到您退出应用程序为止)。
如果这有帮助,我强烈建议您将逻辑封装在一个小帮助器中。为了简单起见,可以将其存储为单例。
class HotKeyController {
static var instance = HotKeyController()
private init() { }
var hotKey: HotKey? {
didSet {
hotKey.keyDownHandler = { [weak self] in
NSApplication.shared.orderedWindows.forEach({ (window) in
print("woo")
})
}
}
}
}然后在视图控制器中使用以下代码:
class ViewController: NSViewController {
@IBOutlet var pressedLabel: NSTextField!
private var hotKey: HotKey? {
get {
return HotKeyController.instance.hotKey
}
set {
HotKeyController.instance.hotKey = newValue
guard let hotKey = newValue else {
pressedLabel.stringValue = "Unregistered"
return
}
pressedLabel.stringValue = "Registered"
}
}
override func viewDidLoad() {
super.viewDidLoad()
register(self)
// Do any additional setup after loading the view.
}
@IBAction func unregister(_ sender: Any?) {
hotKey = nil
print("the hot key is ", hotKey?.keyCombo)
}
@IBAction func register(_ sender: Any) {
hotKey = HotKey(keyCombo: KeyCombo(key: .j, modifiers: [.command, .shift]))
print("the hot key is ", hotKey?.keyCombo)
}
}从长远来看,您将希望在HotKeyController的私有初始化器中实现UserDefaults-based热键存储和恢复,以使设置“固定不变”。
https://stackoverflow.com/questions/63986574
复制相似问题