【问题标题】:Reload TextField keyboard in SwiftUI在 SwiftUI 中重新加载 TextField 键盘
【发布时间】:2022-02-01 17:03:19
【问题描述】:

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

struct ContentView: View {

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

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

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

我看到有一个way to wrap UITextField 以便键盘动态更新。但我想知道/希望在 SwiftUI 中有一种方法可以做到这一点。也许有办法访问UITextViewreloadInputViews() 方法?任何帮助将不胜感激。

【问题讨论】:

    标签: swiftui textfield


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-05-17
      • 2019-12-23
      • 1970-01-01
      • 2020-08-04
      • 2021-05-22
      • 2019-10-24
      • 2021-08-04
      • 2021-05-04
      • 2021-09-30
      相关资源
      最近更新 更多