Search code examples
iosswiftuipickerview

Programmatically scroll a Picker View up or down


As you can see here, the toolbar above the Picker View has both next and back button, and I want to scroll the Picker view programmatically up and down when the user clicks on those buttons. I am not able to get how to do the same. Please help me in understanding how to implement the same.

enter image description here


Solution

  • Your< and > buttons need to have actions associated, let's do an example for "selectNext". I am going to assume you only have one component:

    var myElements: [SomeType] = // whichever elements you are displaying
    var pickerView: UIPickerView // maybe an outlet or an initialised programmatically variable
    
    @objc func selectNext() {
        let currentSelectedRow = pickerView.selectedRow(inComponent: 0)
        guard currentSelectedRow < myElements.count else {
            return
        }
        if currentSelectedRow + 1 < myElements.count {
            pickerView.selectRow(currentSelectedRow + 1, inComponent: 0, animated: true)
        } else { // next element is 0th of list
            pickerView.selectRow(0, inComponent: 0, animated: false)
        }        
    }
    

    The selectPrevious function would follow the same suit. You can also add more checks to make sure that the element you are going to select is not out of bounds, or that myElements contains elements.