I have a PickerView and a Label like this:
I want to, when I change the value of each row in components, it will assign the value to the label above.
For example: when I choose "Blue" in the first component and "Two" in the second component it will assign "Blue Two" to the Label.
I have tried like this, but it doesn't work well, it goes crash when I select the sixth value in the second component:
import UIKit
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet var colorLabel: UILabel!
let colors = ["Red", "Green", "Blue", "Black", "White"]
let numbers = ["One", "Two", "Three", "Four" ,"Five", "Six", "Seven"]
var array = [[String]]()
override func viewDidLoad() {
super.viewDidLoad()
array = [colors, numbers]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return array.count
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return array[component].count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return array[component][row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
colorLabel.text = component == 0 ? array[component][row] + " " + array[component][row] : array[component][row] + " " + array[component][row]
}
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
var selectedValueFirstRow = pickerView.selectedRowInComponent(0)
var selectedValueSecondRow = pickerView.selectedRowInComponent(1)
colorLabel.text = colors[selectedValueFirstRow] + " " + numbers[selectedValueSecondRow]
}
Your code is crashing because its out of index for the first array