如何解决UIPickerView 作为 SwiftUI 中 TextField() 的输入
我正在尝试在 SwiftUI 中将选择器视图显示为 TextField() 的键盘输入类型。我想显示一个用户可以选择的国籍列表。
解决方法
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)
}
}
}
这里是输出
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。