通常我会使用
presentTextInputControllerWithSuggestions()
显示 TextInput 字段。但这在 swiftUI 中不可用,因为它是 WKInterfaceController 的函数。我必须使用 WKInterfaceController 吗?
我在文档中找不到任何内容。
您可以在 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
}
}
}
这可以通过 SwiftUI 中的 TextField 来完成。
在 WatchOS 9 中,我们现在有了 TextFieldLink
您可以使用任何视图作为打开文本输入的按钮,而不是使用 TextField
struct ContentView: View {
@State private var value = ""
var body: some View {
VStack {
Text(value)
TextFieldLink {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
} onSubmit: { value in
self.value = value
}
}
.padding()
}
}