如何在Swift中创建自定义UIPickerView来连接UITextField

rryofs0p  于 2023-05-05  发布在  Swift
关注(0)|答案(1)|浏览(139)

我试着创建一个自定义的UIPickerView,因为我需要许多不同的自定义PickerView来连接到我的一个UIViewController。
我创建以下代码:

let estadosArray = ["AC","AL","AP","AM","BA","CE","ES","GO","MA","MT","MS","MG","PA","PB","PR","PE","PI","RJ","RN","RS","RO","RR","SC","SP","SE","TO","DF"]

class EstadosPickerView: UIViewController {

let myTextField: UITextField
var myPickerView: UIPickerView = UIPickerView()

init(ufExpedicaoTextField: UITextField) {
    self.myTextField = ufExpedicaoTextField
    myTextField.inputView = myPickerView
    super.init(nibName: nil, bundle: nil)
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

}

extension EstadosPickerView: UIPickerViewDelegate, UIPickerViewDataSource {

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return estadosArray.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return estadosArray[row]
}
    
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    myTextField.text = estadosArray[row]
    myTextField.resignFirstResponder()
}

}

当我在UIViewController上单击UITextField时,UIPickerView出现,但它不显示任何数据。是空的
我的代码没有显示任何数据,这是什么问题?

pkwftd7m

pkwftd7m1#

也许您忘记了选择器的定义dataSource和委托

class EstadosPickerView: UIViewController {
....
    override func viewDidLoad() {
        super.viewDidLoad()
        myPickerView.delegate = self
        myPickerView.dataSource = self
    }
}

相关问题