1

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

4

1 回答 1

5

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

但是你可以使用 UITextfield 和 UIPickerView 使用 UIViewRepresentable

首先制作 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)
        
     }
 }
}

这是输出

在此处输入图像描述

于 2021-02-05T08:29:12.927 回答