Typically I would use presentTextInputControllerWithSuggestions() to show the TextInput field. But this isn't available in swiftUI because it is a function of WKInterfaceController. Do I have to use the WKInterfaceController for this?
I couldn't find anything in the documentation.
3 Answers
You can use extension for View in 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)
}
}
}
Example:
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
}
}
}
2 Comments
Tobias Fünke
Thanks! Quick question: should I just be able to call this from my ContentView? I added this extension beneath the
struct ContentView: View block, and I'm trying to call it from Button(action: { presentInputControler(..) }) but when I click the button in preview, nothing happens.Андрій Вахній
@TobiasFünke I've added an example to the answer how to use this extension
This would be done through a TextField in SwiftUI.
4 Comments
Celina
So simple and works like a charm. Thank you very much!
CodeChimp
Although I'm using TextField successfully in WatchOS I can't find how to add suggestions to the input. Any pointers?
Edison
Does anyone know which is the convention or Apple recommend way? TextField or traditional WatchKit text input controller? I've designed my Textfield so it looks like a button anyway, but I'd love to know what the Apple way is for small screens.
Vlad Antonov
@Edison Since WatchOS 9 you can use TextFieldLink for this purposes
In WatchOS 9 now we have TextFieldLink
Instead of using TextField you can use any view as a button for opening text input
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()
}
}
2 Comments
user2330482
thank you for your comment - however does this work for you on watchOS 10.1 beta? It closes itself for me on the beta for some reason, can you confirm?
Duck
WOW!!!!!!!!!!!!!!!!!!!! You saved my bacon. Cannot upvote you enough! Works smoothly on the Apple Watch!