如何在 swiftUI 中为 WatchOS 使用 TextInput

Cel*_*ina 5 apple-watch watchkit swiftui

通常我会presentTextInputControllerWithSuggestions()用来显示 TextInput 字段。但这在 swiftUI 中不可用,因为它是 WKInterfaceController 的一个函数。我必须为此使用 WKInterfaceController 吗?我在文档中找不到任何内容。

Анд*_*ній 11

您可以在 SwiftUI 中使用 View 扩展:

extension View {
    typealias StringCompletion = (String) -> Void
    
    func presentInputController(withSuggestions suggestions: [String], completion: @escaping StringCompletion) {
        WKExtension.shared()
            .visibleInterfaceController?
            .presentTextInputController(withSuggestions: suggestions,
                                        allowedInputMode: .plain) { result in
                
                guard let result = result as? [String], let firstElement = result.first else {
                    completion("")
                    return
                }
                
                completion(firstElement)
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

例子:

struct ContentView: View {

    var body: some View {
        Button(action: {
            presentInputController()
        }, label: {
            Text("Press this button")
        })
    }
    
    private func presentInputController() {
        presentInputController(withSuggestions: []) { result in
            // handle result from input controller
        }
    }
}
Run Code Online (Sandbox Code Playgroud)