How to Scroll to Specific Row in UIPickerView In iOS Swift 3

3.1k views Asked by At

I have a UIPickerView with values 0...250. There is 2 Components in UIPickerView. In First component i am displaying these values. but i want to detect scrolling method of the UIPickerView. because when pickerView appears the value I would like to display is 75. means pickerView is scroll to row number 75. and user can scroll up and down the picker with values 0...250. I have tried this code in UIPickerView titleForRow row: Int method

pickerView.selectRow(75, inComponent: 0, animated: true)

in this case when pickerView appears the selected value is 75. Below is exactly what i want

enter image description here

but the problem is that on scrolling pickerView my app crash with following error

[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

anyone help me please thanks in advance :-)

2

There are 2 answers

3
Ravi B On

While inside the viewDidLoad method, your picker is empty. You can do this if you delay execution of the select call until after the data is finished loading. Likely one cycle will be enough.

You can add it in viewDidAppear or viewWillAppear

0
mini coder On

It happens because you are scrolling to index 75 before the pickerView has initialised that cell. UIPickerView only initialises visible cells first, and initialise rest of the cells as you scroll.

Do this in viewDidAppear

override func viewDidAppear(_ animated: Bool) {
    pickerView.selectRow(75, inComponent: 0, animated: true)
}