Search code examples
iosswiftuipickerview

What is the meaning of "component" in a UIPickerView.selectedRowInComponent?


Using Swift in Xcode, I want to make:

1) A PICKER, with data from an array

2) A BUTTON, when pressed will update a LABEL with the text from a selected row of the PICKER

My code currently:

var array = ["Sydney", "London", "Washington", "Tokyo", "San Francisco"]

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

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

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

@IBOutlet weak var PICKER: UIPickerView!

@IBOutlet weak var LABEL: UILabel!

@IBAction func BUTTON(sender: AnyObject) {
    LABEL.text = array[PICKER.selectedRowInComponent(0)]
}

So far everything worked. But I have 2 questions:

1) Should I put a "0" in PICKER.selectedRowInComponent? What does it mean? Because it didn't work without a number or with any other number. Wouldn't that mean selecting only the first row (instead of selecting the row the user has selected)?

2) How do I make the PICKER to show the middle item of an array by default and not the first item when the app loads (e.g. Washington in this case)?


Solution

  • Pickers can have multiple wheels (components). For example, you might have separate wheels for each digit, or you might have day, month, and year wheels. They are numbered starting at 0. So "Component 0" is just the first wheel (and you only have one).

    Selecting rows is done by calling selectRow(inComponent:animated:).