Reputation: 127
I am trying to change the keyboard type of a single TextField
dynamically. That is, I have something like this:
struct ContentView: View {
@Binding var keyboardType: UIKeyboardType
@State var searchText = ""
var body: some View {
TextField("placeholder", text: $searchText).keyboardType(keyboardType)
}
}
Now, dynamically, I would like the keyboard to change from one keyboard style to the other, depending on what keyboardType
is. However, what I've found is that keyboardType
changes, but the soft keyboard doesn't. Rather, the keyboard stays the same, and only after I dismiss the keyboard and bring it back up, does it show something different.
I see that there is a way to wrap UITextField
so that the keyboard updates dynamically. But I was wondering/hoping there'd be a way to do this in SwiftUI. Perhaps there's a way to access UITextView
's reloadInputViews()
method? Any help would be appreciated.
Upvotes: 0
Views: 809
Reputation: 12115
You can use @FocusState
– disable focus, change the keyboard, then focus again:
struct ContentView: View {
@State var mykeyboard = UIKeyboardType.numberPad
@State var searchText = ""
@FocusState var focus: Bool
var body: some View {
VStack {
Divider()
HStack {
TextField("placeholder", text: $searchText)
.keyboardType(mykeyboard)
.focused($focus)
Button("Submit") {
focus = false
}
}
Divider()
HStack {
Button("Numbers") {
focus = false
mykeyboard = .numberPad
focus = true
}
Button("EMail") {
focus = false
mykeyboard = .emailAddress
focus = true
}.padding()
Button("Alphabet") {
focus = false
mykeyboard = .alphabet
focus = true
}
}
}
.padding()
.buttonStyle(.bordered)
}
}
Upvotes: 1