【问题标题】:Set a default Value of a UIPickerView: index beyond bounds设置 UIPickerView 的默认值:超出范围的索引
【发布时间】:2020-06-03 20:01:02
【问题描述】:

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

【问题讨论】:

    标签: swift uipickerview


    【解决方案1】:

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

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

    【讨论】:

    • 好的,现在当我第一次打开这个活动时,微调器可以在困难的位置正确打开,但是如果我在这个微调器中选择另一个位置(例如我手动将它们调整为简单)然后打开再次执行此活动,然后发生相同的错误
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 1970-01-01
      相关资源
      最近更新 更多