How to detect keyboard events in SwiftUI on macOS?

前端 未结 2 909
青春惊慌失措
青春惊慌失措 2020-12-09 05:19

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 d

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 06:16

    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:

提交回复
热议问题