0

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 Answers1

1

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)"
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Alright...Gotcha! Thank you! So I suppose I'm not totally understanding how I need to associate the color with the number that I want to appear. Right now, I've got it set the simple way and it's returning whatever color I've chosen. How can I program it so whenever I choose the color it provides the number? – WhatA BearThinks Dec 04 '17 at 20:54
  • The number is the picker row. The color is obtained from the `colors` array based on the number. – rmaddy Dec 04 '17 at 20:55
  • What if the number I'd like to display is 22 or 23 or 51? OR WHAT if it's not a number at all? But some other text? – WhatA BearThinks Dec 04 '17 at 20:58
  • Then you need different code. If you have a specific requirement then put that information clearly in your question. As of now, you stated you want 1, 2, 3 which matches the order of the colors in your `colors` array so there is a simple implementation. But for some other seemingly arbitrary mapping of numbers to colors, you need a different solution. But that's not what you asked in your question. – rmaddy Dec 04 '17 at 21:00
  • Understood! I will change it to more specific. Thanks for the suggestion! – WhatA BearThinks Dec 05 '17 at 16:59