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)?
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:)
.
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 where
0
1
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With