Programmer1994
Programmer1994

Reputation: 975

Getting selected value of a UIPickerViewControl in Swift

How can I get the selected value of a UIPickerViewControl in Swift?

I tried something like this:

labelTest.text = Spinner1.selectedRowInComponent(0).description

But this only returns the selected index. I need the value.

Anyone who knows how to do this?

Upvotes: 33

Views: 72924

Answers (5)

Jeffrey Kozik
Jeffrey Kozik

Reputation: 549

The accepted answer is right except for it should include a typecast from String to Int:

var selectedValue = pickerViewContent[Int(pickerView.selectedRowInComponent(0))!]

Upvotes: 1

Wayne Henderson
Wayne Henderson

Reputation: 267

All the answers so far presuppose you can easily connect the selected row back to the original data array. The solution is fairly easy if you can do that, but the question specifically addresses the case where the original array is not readily available. For instance I have 3 pickers in table cells that expand when one row is tapped, and they show 3 different arrays.

It would save me a lot of trouble if I could simply retrieve the selected text from the picker itself, perhaps in the code for my custom cell, instead of having to figure out which picker, which data array, which row and so on.

If the answer is that you can't, that's OK, I'll sort it all out. But the question is whether there's a shortcut.

Upvotes: 1

Jeacovy Gayle
Jeacovy Gayle

Reputation: 457

Swift 4

let selectedYearPicker = pickerData[yearPicker.selectedRow(inComponent: 
print(selectedYearPicker)

Or

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent  component: Int) {
    let yearValueSelected = pickerData[row] as String
    print(yearValueSelected)
}

Upvotes: 8

Marcos Reboucas
Marcos Reboucas

Reputation: 3489

Swift 3: supose you want the String value of each row selected

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        let valueSelected = yourDataSourceArray[row] as String
 }

Upvotes: 8

Omkar Guhilot
Omkar Guhilot

Reputation: 1698

you will have to set the picker view delegate to self and override this function

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
   {
        // use the row to get the selected row from the picker view
        // using the row extract the value from your datasource (array[row])
    }

or

you can use this to extract as per your usage

var selectedValue = pickerViewContent[pickerView.selectedRowInComponent(0)]

where pickerViewContent is your array of dataSource

Upvotes: 82

Related Questions