在 SwiftUI 中重新加载 TextField 键盘

Reload TextField keyboard in SwiftUI

我正在尝试动态更改单个 TextField 的键盘类型。也就是说,我有这样的东西:

struct ContentView: View {

  @Binding var keyboardType: UIKeyboardType
  @State var searchText = ""

  var body: some View {
    TextField("placeholder", text: $searchText).keyboardType(keyboardType)
  }
}

现在,动态地,我希望键盘从一种键盘样式更改为另一种键盘样式,具体取决于 keyboardType 是什么。但是,我发现 keyboardType 发生了变化,而软键盘却没有。相反,键盘保持不变,只有在我关闭键盘并将其重新打开后,它才会显示不同的内容。

我看到有一个 可以让键盘动态更新。但我 wondering/hoping 在 SwiftUI 中有一种方法可以做到这一点。也许有办法访问 UITextViewreloadInputViews() 方法?任何帮助将不胜感激。

您可以使用 @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)
    }
}