如何在 swiftUI 中为 WatchOS 使用 TextInput
How do I use TextInput for WatchOS in swiftUI
通常我会使用 presentTextInputControllerWithSuggestions()
来显示 TextInput 字段。但这在 swiftUI 中不可用,因为它是 WKInterfaceController 的一个函数。我必须为此使用 WKInterfaceController 吗?
我在文档中找不到任何内容。
这将通过 SwiftUI 中的 TextField 完成。
您可以在 SwiftUI 中使用视图扩展:
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)
}
}
}
示例:
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
}
}
}
通常我会使用 presentTextInputControllerWithSuggestions()
来显示 TextInput 字段。但这在 swiftUI 中不可用,因为它是 WKInterfaceController 的一个函数。我必须为此使用 WKInterfaceController 吗?
我在文档中找不到任何内容。
这将通过 SwiftUI 中的 TextField 完成。
您可以在 SwiftUI 中使用视图扩展:
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)
}
}
}
示例:
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
}
}
}