How to detect keyboard events in SwiftUI on macOS?

試著忘記壹切 提交于 2020-05-23 10:19:49

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!