Search code examples
iosswiftuipickerview

More than 1 UIPickerView Swift


I was trying to make a simple app with 2 UIPickerViews and when I put in the second one, it just contains the same data as the first. I've declared the functions for inserting the data into the first one:

var typesOfData = ["KB","MB","GB"]
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return typesOfData.count
}

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

but I need to know how to declare these functions for the second UIPickerView.


Solution

  • You can use the same delegate methods to populate both UIPickerViews. Just populate them conditionally depending on which UIPickerView you're dealing with. For example, if your first UIPickerView's called firstPickerView and your second UIPickerView is populated by secondDataSet:

    var typesOfData = ["KB","MB","GB"]
    var secondDataSet = ["A","B","C"]
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if pickerView == firstPickerView {
            return typesOfData.count
        } else { // if it's the second picker view
            return secondDataSet.count
        }
    }
    
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        if pickerView == firstPickerView {
            return typesOfData[row]
        } else {
            return secondDataSet[row]
        }
    }