[英]Reload TextField keyboard in SwiftUI
I am trying to change the keyboard type of a single TextField
dynamically.我正在尝试动态更改单个TextField
的键盘类型。 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.现在,动态地,我希望键盘从一种键盘样式更改为另一种键盘样式,具体取决于keyboardType
是什么。 However, what I've found is that keyboardType
changes, but the soft keyboard doesn't.但是,我发现keyboardType
类型发生了变化,但软键盘没有。 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.我看到有一种方法可以包装UITextField
以便键盘动态更新。 But I was wondering/hoping there'd be a way to do this in SwiftUI.但我想知道/希望在 SwiftUI 中有一种方法可以做到这一点。 Perhaps there's a way to access UITextView
's reloadInputViews()
method?也许有一种方法可以访问UITextView
的reloadInputViews()
方法? Any help would be appreciated.任何帮助,将不胜感激。
You can use @FocusState
– disable focus, change the keyboard, then focus again:您可以使用@FocusState
– 禁用焦点,更改键盘,然后再次聚焦:
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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.