【发布时间】:2019-11-16 02:23:18
【问题描述】:
通常我会使用presentTextInputControllerWithSuggestions() 来显示TextInput 字段。但这在 swiftUI 中不可用,因为它是 WKInterfaceController 的一个函数。我必须为此使用 WKInterfaceController 吗?
我在文档中找不到任何内容。
【问题讨论】:
标签: watchkit apple-watch swiftui
通常我会使用presentTextInputControllerWithSuggestions() 来显示TextInput 字段。但这在 swiftUI 中不可用,因为它是 WKInterfaceController 的一个函数。我必须为此使用 WKInterfaceController 吗?
我在文档中找不到任何内容。
【问题讨论】:
标签: watchkit apple-watch swiftui
这将通过 SwiftUI 中的 TextField 来完成。
【讨论】:
您可以在 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)
}
}
}
例子:
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
}
}
}
【讨论】:
struct ContentView: View 块下添加了这个扩展,我试图从Button(action: { presentInputControler(..) }) 调用它,但是当我点击预览中的按钮时,什么也没有发生。