I am trying to set default value for PickerView element but there is an error when running: index beyond the bonds, My intention is to star from "Difficult" option as default, that is, nivel = 3.
@IBOutlet weak var spinner: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
self.spinner.delegate = self
self.spinner.dataSource = self
nivel = 3
lista_parametros = ["All","Easy","Medium","Dificult"]
self.spinner.selectRow(4, inComponent: nivel, animated: true) /// the error is here !! when running
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return lista_parametros.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return lista_parametros[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
nivel = row
UserDefaults.standard.set(nivel,forKey: "nivel")
}
Index starts from 0
. So you should modify it to this:
spinner.selectRow(3, inComponent: nivel, animated: true)