SwiftUI iOS - 如何使用捕获的硬件按键事件

SwiftUI iOS - how to use captured hardware key events

如何在 SwiftUI 中使用按键信息? 我尝试使用 @EnvironmentObject 与我的 SwiftUI 共享密钥,但我每次都会在 sendKeybKey 中崩溃:线程 1:致命错误:找不到 UserData 类型的 ObservableObject。作为此视图的祖先,UserData 的 View.environmentObject(_:) 可能缺失。 在 .environmentObject 中已经在 SceneDelegate 中使用了,但是错了吗? 我的代码:

class KeyTestController<Content>: UIHostingController<Content> where Content: View {
@EnvironmentObject var userData: UserData
override func becomeFirstResponder() -> Bool {
        true
}
override var keyCommands: [UIKeyCommand]? {
        var keys = [UIKeyCommand]()

        for num in "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!\r" {
        keys.append(
                    UIKeyCommand(
                                    input:String(num),
                                    modifierFlags: [],
                                    action:
                                    #selector(sendKeybKey)
                                )
                    )
    }
    return keys
}
@objc func sendKeybKey(_ sender: UIKeyCommand) {
        userData.collectChar = sender.input ?? ""
        print(">>> test was pressed \(sender.input ?? "")")
}

}

在场景代理中

 if let windowScene = scene as? UIWindowScene {
    let window = UIWindow(windowScene: windowScene)
    window.rootViewController = KeyTestController/*UIHostingController*/(
        rootView: myList()
        .environmentObject(UserData())
    )
    self.window = window
    window.makeKeyAndVisible()
}

和用户数据:

    final class UserData: ObservableObject  {
    @Published var datasetUIIdata: [DatasetUII] = []
    @Published var collectChar : String = ""
    @Published var collectText : String = ""
}

我的 SwiftUI 视图

struct myList: View {
@EnvironmentObject var userData: UserData

var body: some View {
    VStack {
        HStack {
                Text("Key\(userData.collectChar)").font(.largeTitle)
            }
        .padding()
        List {
            ForEach(userData.datasetUIIdata, id: \.self) { (item) in
                Text(item.userName)
            }
            .onDelete(perform: delete)
        }
        .padding()
    }
}
func delete(at offsets: IndexSet) {
    userData.datasetUIIdata.remove(atOffsets: offsets)
}

}

有人愿意为新手提供快速帮助吗?

谢谢!

瓦尔德玛

控制器中不需要@EnvironmentObjectUserData是引用类型,所以你可以直接在视图和控制器中注入相同的对象。

class KeyTestController<Content>: UIHostingController<Content> where Content: View {
      var userData: UserData

那么接下来的创作会是这样

 if let windowScene = scene as? UIWindowScene {
    let window = UIWindow(windowScene: windowScene)

    let userData = UserData()
    let contentView = myList().environmentObject(userData)      // in view !!

    let controller = KeyTestController(rootView: contentView)
    controller.userData = userData                              // in controller !!

    window.rootViewController = controller