简体   繁体   中英

Reload TextField keyboard in SwiftUI

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.

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)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM