UIPickerView 作为 SwiftUI 中 TextField() 的输入

UIPickerView as input for TextField() in SwiftUI

我正在尝试在 SwiftUI 中将选择器视图显示为 TextField() 的键盘输入类型。我想显示一个国籍列表,然后用户可以 select.

SwiftUI 的 TextField 没有像 UITextField 那样的 inputView 属性。

但是您可以通过 UIViewRepresentable 使用 UITextfield 和 UIPickerView

首先制作TextFieldWithInputView.swift文件并在其中添加以下代码

struct TextFieldWithInputView : UIViewRepresentable {

  var data : [String]
  var placeholder : String

  @Binding var selectionIndex : Int
  @Binding var selectedText : String?

  private let textField = UITextField()
  private let picker = UIPickerView()

  func makeCoordinator() -> TextFieldWithInputView.Coordinator {
       Coordinator(textfield: self)
  }

  func makeUIView(context: UIViewRepresentableContext<TextFieldWithInputView>) -> UITextField {
       picker.delegate = context.coordinator
       picker.dataSource = context.coordinator
       picker.backgroundColor = .gray
       picker.tintColor = .black
       textField.placeholder = placeholder
       textField.inputView = picker
       textField.delegate = context.coordinator
       return textField
  }

  func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<TextFieldWithInputView>) {
       uiView.text = selectedText
  }

  class Coordinator: NSObject, UIPickerViewDataSource, UIPickerViewDelegate , UITextFieldDelegate {

       private let parent : TextFieldWithInputView

       init(textfield : TextFieldWithInputView) {
            self.parent = textfield
       }

       func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return 1
       }
       func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return self.parent.data.count
       }
       func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return self.parent.data[row]
       }
       func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            self.parent.$selectionIndex.wrappedValue = row
            self.parent.selectedText = self.parent.data[self.parent.selectionIndex]
            self.parent.textField.endEditing(true)

       }
       func textFieldDidEndEditing(_ textField: UITextField) {
            self.parent.textField.resignFirstResponder()
       }
 }
}

然后,您可以在您的 contentView 中使用它,如下所示

struct ContentView : View {

  @State var country : String? = nil
  @State var arrCountry = ["India","USA","France"] //Here Add Your data
  @State var selectionIndex = 0

  var body : some View {
      VStack {
        TextFieldWithInputView(data: self.arrCountry, placeholder: "Select your country", selectionIndex: self.$selectionIndex, selectedText: self.$country)
            .frame(width: 300, height: 50)
            .border(Color.black)
        
     }
 }
}

这是输出