Search code examples
swift3uipickerview

Get value from Pickerview when it is not user accessible


I am working on an app that uses a UIPickerView in the same way a slot machine would work. The user cannot spin it and it does not recognize user touches. The selection is randomized after a button pressed.

The question is, how can I get the data of the pickerview's row?

pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) does not work since the user does not really select anything.


Solution

  • There is a method to get the selected row:

    func selectedRow(inComponent component: Int) -> Int
    

    Parameters

    component : A zero-indexed number identifying a component of the picker view.

    Return value

    A zero-indexed number identifying the selected row, or -1 if no row is selected.

    Use it:

    let row = picker.selectedRow(inComponent: 0)
    let item = pickerArray[row]
    

    picker is the UIPickerView instance.
    pickerArray is the data source array of the picker view.