Tiago Sousa
Tiago Sousa

Reputation: 138

How to get the text of a UIPickerView?

I would like to know if i could get the selected String of a PickerView because when using the method func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) i only know the row selected and what i am using is if i know the row i know the position on the array i used to load the PickerViews but i wanted to do this pickerView.text to do something like this

if (pickerView.text == "hello"){
    doSomething(pickerView.text);
}

Because now i have to do much more code lines to do something like this

Sorry i forget to mention, i have 3 PickerView and to know the String is in the third picker view i have to see what row is selected in each one

Upvotes: 2

Views: 1812

Answers (2)

rob mayoff
rob mayoff

Reputation: 385540

extension UIPickerView {
    func selectedTitleForComponent(component: Int) -> String? {
        let row = selectedRowInComponent(component)
        return dataSource.pickerView(pickerView, titleForRow:row, forComponent:component)
    }
}

Then:

if pickerView.selectedTitleForComponent(0) == "hello" {
    ...
}

Upvotes: 0

matt
matt

Reputation: 534950

i only know the row selected and what i am using is if i know the row i know the position on the array

And that's the answer. Don't fight the framework; use it. The framework uses Model-View-Controller. The UIPickerView is view; it has no data. You have the data, and given the row, you can fetch it from the model.

Upvotes: 1

Related Questions