Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force UIPickerView.selectRow call didSelectRow method?

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) {

}
like image 862
Hattori Hanzō Avatar asked Dec 02 '22 12:12

Hattori Hanzō


2 Answers

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

like image 72
Sh_Khan Avatar answered Dec 22 '22 09:12

Sh_Khan


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.

like image 26
Au Ris Avatar answered Dec 22 '22 09:12

Au Ris