本文介绍了SwiftUI iOS - 如何捕获硬件按键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 iOS 开发的新手.按照教程,我使用 SwiftUI 创建了一个简单的计算器.

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

我的 iPad 上有一个键盘,我希望能够使用键盘输入值.

I have a keyboard attached to my iPad, and I would like to be able to enter values using the keyboard.

如何在 SwiftUI 应用程序(没有文本字段)中捕获和处理硬件键盘事件?我尝试在 SceneDelegate (UIResponder) 上使用 keyCommands,如下所示,但这对我不起作用.只要我按下 iPad 上的任意键,我就会在 XCode 跟踪视图中看到与守护进程的连接已失效".

How can I capture and handle hardware keyboard events in a SwiftUI app (with no text field) ? I have tried to use the keyCommands on the SceneDelegate (UIResponder) as shown here, but that doesn’t work for me. As soon as I press any key on my iPad, I get "Connection to deamon was invalidated" in the XCode trace view.

 class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    var window: UIWindow?

    override var canBecomeFirstResponder: Bool {
        return true;
    }
    override var keyCommands: [UIKeyCommand]? {
        return [
            UIKeyCommand(input: "a", modifierFlags: [], action: #selector(test)),
            UIKeyCommand(input: UIKeyCommand.inputLeftArrow, modifierFlags: [], action: #selector(test))
        ]
    }

    @objc func test(_ sender: UIKeyCommand) {
        print("test was pressed")
    }

谢谢

推荐答案

它需要重写托管视图控制器,并且一切正常.使用 Xcode 11.2/iOS 13.2 测试

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

这是示例代码

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")
    }

}

SceneDelegate下面的某处

window.rootViewController = KeyTestController(rootView: contentView)

这篇关于SwiftUI iOS - 如何捕获硬件按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 13:53