设置 UIPickerView 的默认值:索引超出范围

Set a default Value of a UIPickerView: index beyond bounds

我正在尝试为 PickerView 元素设置默认值,但在 运行 时出现错误:超出债券的索引,我的意图是从 "Difficult" 选项作为默认值,即,尼维尔 = 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")
 }

索引从 0 开始。所以你应该修改成这样:

spinner.selectRow(3, inComponent: nivel, animated: true)

必须在第一个参数处进行选择:

self.spinner.selectRow(nivel, inComponent: 0, animated: true)