SwiftUI iOS - how to capture hardware key events

后端 未结 1 1648
伪装坚强ぢ
伪装坚强ぢ 2021-01-13 01:58

I’m new to iOS development. Following a tutorial I have created a simple calculator using SwiftUI.

I have a keyboard attached to my iPad, and I would like to be able

相关标签:
1条回答
  • 2021-01-13 02:05

    It needs to override hosting view controller instead and all works. Tested with Xcode 11.2 / iOS 13.2

    Here is example code

    class KeyTestController<Content>: UIHostingController<Content> where Content: View {
    
        override func becomeFirstResponder() -> Bool {
            true
        }
    
        override var keyCommands: [UIKeyCommand]? {
            return [
                UIKeyCommand(input: "1", modifierFlags: [], action: #selector(test)),
                UIKeyCommand(input: "0", modifierFlags: [], action: #selector(test)),
                UIKeyCommand(input: UIKeyCommand.inputLeftArrow, modifierFlags: [], action: #selector(test))
            ]
        }
    
        @objc func test(_ sender: UIKeyCommand) {
            print(">>> test was pressed")
        }
    
    }
    

    and somewhere in SceneDelegate below

    window.rootViewController = KeyTestController(rootView: contentView)
    
    0 讨论(0)
提交回复
热议问题