问题
How can I detect keyboard events in a SwiftUI view on macOS?
I want to be able to use key strokes to control items on a particular screen but it's not clear how I detect keyboard events, which is usually down by overriding the keyDown(_ event: NSEvent) in NSView.
回答1:
There is no built-in native SwiftUI API for this, so far.
Here is just a demo possible approach. Tested with Xcode 11.4 / macOS 10.15.4
struct KeyEventHandling: NSViewRepresentable {
class KeyView: NSView {
override var acceptsFirstResponder: Bool { true }
override func keyDown(with event: NSEvent) {
super.keyDown(with: event)
print(">> key \(event.charactersIgnoringModifiers ?? "")")
}
}
func makeNSView(context: Context) -> NSView {
let view = KeyView()
DispatchQueue.main.async { // wait till next event cycle
view.window?.makeFirstResponder(view)
}
return view
}
func updateNSView(_ nsView: NSView, context: Context) {
}
}
struct TestKeyboardEventHandling: View {
var body: some View {
Text("Hello, World!")
.background(KeyEventHandling())
}
}
Output:
来源:https://stackoverflow.com/questions/61153562/how-to-detect-keyboard-events-in-swiftui-on-macos