PickerView to return certain text string based on picker selection

726 views Asked by At

What I would like to do is have a certain text string to appear depending on what is selected from the Picker. For instance, the choices Blue, Green, and Yellow are available for selection in the picker. When you choose Blue some text (ex. I LOVE the ocean!) is output to a label.

I've got everything working, except I can't change the output from anything other than what was selected in the picker.

Example of the code in question,

let colors = ["Blue", "Green", "Yellow"]

func numberOfComponents(in pickerView: UIPickerView) -> Int
{
    return 1
}

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

}

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

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
    label.text = colors[row]
}    //but I want this to return a text string when Blue is 'picked', another different string when Green is 'picked', and a third sting when Yellow is 'picked'

I have it set so the data appears on a label once a selection in the pickerView has been made, but like I said, I can only get the data from the pickerView itself to appear. I would like to have some other data (that you don't see) appear based on your selection in the picker.

1

There are 1 answers

5
rmaddy On

The code you put in didSelectRow is setting the color name. If you want the selected row number, then set the label to the selected row.

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
    label.text = "\(row + 1)"
}