不幸的是,键盘事件处理是其中一个令人痛苦的明显问题,SwiftUI 首先是为 iOS 设计的,而 macOS 是事后才想到的。
如果您尝试检测的键是鼠标单击的修饰符,例如cmd
, option
, or shift
,您可以使用.modifiers
with onTapGesture
以区别于未修改的onTapGesture
。在这种情况下,我的经验是你想要.onTapGesture
调用使用.modifiers
to precede未修改的。
处理任意视图的一般按键事件需要离开 SwiftUI。
如果您只需要一个视图,一种可能性是使用AppKit
这样你就可以通过普通的Cocoa接收键盘事件firstResponder
机制,然后将该视图包装在 SwiftUI 中NSViewRepresentable
。在这种情况下,你的包裹NSView
会更新一些@State
财产在NSViewRespresentable
。许多在 macOS 上使用 SwiftUI 的开发人员都是这样做的。虽然这对于少量视图来说没什么问题,但如果事实证明您必须在 AppKit 中实现大量视图才能使它们在 SwiftUI 中可用,那么您就失去了使用 SwiftUI 的意义。在这种情况下,只需将其设为普通的 Cocoa 应用程序即可。
但还有另一种方法...
您可以使用另一个线程CGEventSource
与 SwiftUI 结合主动轮询键盘状态@EnvironmentObject
or @StateObject
将键盘状态更改传达给 SwiftUIView
对他们感兴趣的人。
假设您想检测何时按下向上箭头。为了检测密钥,我使用了扩展CGKeyCode
.
import CoreGraphics
extension CGKeyCode
{
// Define whatever key codes you want to detect here
static let kVK_UpArrow: CGKeyCode = 0x7E
var isPressed: Bool {
CGEventSource.keyState(.combinedSessionState, key: self)
}
}
当然,您必须使用正确的密钥代码。我有一个gist https://gist.github.com/chipjarred/cbb324c797aec865918a8045c4b51d14包含所有旧的密钥代码。如果您愿意,可以将它们重命名为更 Swifty。列出的名称可追溯到经典 MacOS,并在中定义麦金塔内部.
定义该扩展后,您可以随时测试是否按下了某个键:
if CGKeyCode.kVK_UpArrow.isPressed {
// Do something in response to the key press.
}
注意这些是not键向上或键向下事件。它只是一个布尔值,用于检测执行检查时是否按下了该键。为了使行为更像事件,您需要通过跟踪关键状态更改来自己完成该部分。
有多种方法可以做到这一点,下面的代码并不意味着暗示这是“最好”的方法。这简直就是a方式。无论如何,当应用程序启动时,无论您在哪里进行全局初始化,类似以下代码的内容都会被调用(或被调用)。
// These will handle sending the "event" and will be fleshed
// out further down
func dispatchKeyDown(_ key: CGKeyCode) {...}
func dispatchKeyUp(_ key: CGKeyCode) {...}
fileprivate var keyStates: [CGKeyCode: Bool] =
[
.kVK_UpArrow: false,
// populate with other key codes you're interested in
]
fileprivate let sleepSem = DispatchSemaphore(value: 0)
fileprivate let someConcurrentQueue = DispatchQueue(label: "polling", attributes: .concurrent)
someConcurrentQueue.async
{
while true
{
for (code, wasPressed) in keyStates
{
if code.isPressed
{
if !wasPressed
{
dispatchKeyDown(code)
keyStates[code] = true
}
}
else if wasPressed
{
dispatchKeyUp(code)
keyStates[code] = false
}
}
// Sleep long enough to avoid wasting CPU cycles, but
// not so long that you miss key presses. You may
// need to experiment with the .milliseconds value.
let_ = sleepSem.wait(timeout: .now() + .milliseconds(50))
}
}
这个想法只是让一些代码定期轮询关键状态,将它们与以前的状态进行比较,在它们发生变化时调度适当的“事件”,并更新以前的状态。上面的代码通过在并发任务中运行无限循环来实现这一点。它需要创建一个DispatchQueue
与.concurrent
属性。你不能使用它DispatchQueue.main
因为那个队列是serial不是并发的,因此无限循环会阻塞主线程,程序将变得无响应。如果你已经有一个并发DispatchQueue
如果您出于其他原因而使用,则可以只使用该值,而不必创建一个仅用于轮询的值。
但是,任何实现定期轮询基本目标的代码都可以,所以如果您还没有并发DispatchQueue
并且不想创建一个只是为了轮询键盘状态,这将是一个合理的反对意见,这里有一个使用的替代版本DispatchQueue.main
使用称为“异步链接”的技术来避免阻塞/睡眠:
fileprivate var keyStates: [CGKeyCode: Bool] =
[
.kVK_UpArrow: false,
// populate with other key codes you're interested in
]
fileprivate func pollKeyStates()
{
for (code, wasPressed) in keyStates
{
if code.isPressed
{
if !wasPressed
{
dispatchKeyDown(code)
keyStates[code] = true
}
}
else if wasPressed
{
dispatchKeyUp(code)
keyStates[code] = false
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(50))
{
// The infinite loop from previous code is replaced by
// infinite chaining.
pollKeyStates()
}
}
// Start up key state polling
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(50)) {
pollKeyStates()
}
有了代码来检测何时按下按键,您现在需要一种方法将其传达给您的 SwiftUIView
s。再说一遍,剥猫皮的方法不止一种。这是一个过于简单的,将更新View
每当按下向上箭头时,但您可能想要实现一些更复杂的东西......可能允许视图指定它们有兴趣响应哪些键。
class UpArrowDetector: ObservableObject
{
@Published var isPressed: Bool = false
}
let upArrowDetector = UpArrowDetector()
func dispatchKeyDown(_ key: CGKeyCode)
{
if key == .kVK_UpArrow {
upArrowDetector.isPressed = true
}
}
func dispatchKeyUp(_ key: CGKeyCode) {
if key == .kVK_UpArrow {
upArrowDetector.isPressed = false
}
}
// Now we hook it into SwiftUI
struct UpArrowDetectorView: View
{
@StateObject var detector: UpArrowDetector
var body: some View
{
Text(
detector.isPressed
? "Up-Arrow is pressed"
: "Up-Arrow is NOT pressed"
)
}
}
// Use the .environmentObject() method of `View` to inject the
// `upArrowDetector`
struct ContentView: View
{
var body: some View
{
UpArrowDetectorView()
.environmentObject(upArrowDetector)
}
}
我在这里提供了一个完整的、可编译的、有效的示例gist https://gist.github.com/chipjarred/e39c48619e591fbf9588af3d3684bed9以您在评论中链接到的代码为图案。它对上面的代码进行了稍微重构,但所有部分都在那里,包括启动轮询代码。
我希望这能为您指明一个有用的方向。