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

问题描述 投票:-1回答:2

我正在尝试为PickerView元素设置默认值,但是运行时出现错误:索引超出了键,我的意图是从“ Difficult”选项开始,默认为nvel = 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")
 }
swift uipickerview
2个回答
1
投票

索引从0开始。因此,您应该将其修改为:


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.