SwiftUI's TextField does not have inputView property like as UITextField.
But You can use UITextfield and UIPickerView using UIViewRepresentable
First make TextFieldWithInputView.swift file and add below code in it
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()
}
}
}
Then, You can use it in your contentView like as below
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)
}
}
}
Here is output
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…