Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 902
Allister Bah Avatar asked Jan 09 '23 09:01

Allister Bah


2 Answers

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:).

like image 162
Rob Napier Avatar answered Jan 10 '23 23:01

Rob Napier


UIPickerView can have multiple wheels (named components), and are numbered starting at 0. For example, a picker view with 3 components looks like the following 3 components picker where

  • the first wheel ("6") is component 0
  • the second wheel ("00") is the component 1
  • the third wheel ("AM") is the component 2

Unrelated to question title, but selecting a row is done by calling selectRow(_:inComponent:animated:)

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

// code...

yourPicker.selectRow(array.count/2, inComponent: 0, animated: true);
like image 26
Dũng Nguyễn Avatar answered Jan 11 '23 00:01

Dũng Nguyễn