Is it possible to call func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
method, when running UIPickerView.selectRow(4, inComponent: 0, animated: false)
or what is right way to archive this?
my implementation
let pickerView = UIPickerView()
pickerView.delegate = self
pickerView.dataSource = self
pickerView.selectRow(0, inComponent: 0, animated: false)
textField.inputView = pickerView
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}
This to select the row
self.yourPickerViewName.selectRow(2, inComponent: 0, animated: true)
and this to trigger the method
self.pickerView(self.yourPickerViewName, didSelectRow: 2, inComponent: 0)
Combine them to simulate user action
It is definitely not a bug that func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
is not called when you programatically select a row. Documentation says:
Called by the picker view when the user selects a row in a component.
It's a delegate method which gets called only when a user selects a row. So naturally it won't get called if you select a row like this:
pickerView.selectRow(0, inComponent: 0, animated: false)
The hack in your accepted answer works, but it's not good practice to call delegate methods from your view controller. I suggest you to create another method which will do what you want when a row is selected by user or programatically:
e.g.
func doStuff(for row: Int, component: Int) {
// Do your stuff here
}
then in your delegate method:
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
doStuff(for: row, component: component)
}
and when you select a row programatically:
pickerView.selectRow(0, inComponent: 0, animated: false)
doStuff(for: 0, component: 0)
If you need to do something with the pickerView in the doStuff
method you can add another parameter and pass it along when you call it, or access pickerView variable directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With