Search code examples
swiftuipickerview

How to recognize which UIPickerView received event when they share a Data Source


I have 2 UIPickerViews with different datasource arrays. My problem is that I can't figure out how to display both datasources to my 2 picker views.

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return firstArray[row]
}

How can I return both of my datasources to my picker views? The logical solution is to recognize if the first picker view is tapped, use firstArray as datasource, and if the second picker view is tapped, use another array.

Guide me on which properties and methods to use please.


Solution

  • The simplest way is to declare both UIPickerViews as @IBOutlet stored properties at the top of the class (be sure to link these up properly in StoryBoard):

    class MyVC: UIViewController, UIPickerViewDataSource {
        @IBOutlet weak var picker1: UIPickerView?
        @IBOutlet weak var picker2: UIPickerView?
    
        /* set up the delegates ... */
    
        func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            switch pickerView { 
            case picker1: return firstArray[row]
            case picker2: return secondArray[row]
            default: /* print an error or assertion failure */ return nil
            }
        }
    }