我有一个基于此code的包含3个组件的PickerView。右边的两个选择器根据左边的先前选择更改其内容。不幸的是,当我将父选择器更改为行数少于预览数的另一个选择器时,应用程序崩溃:🛑致命错误:索引超出范围。
我试图在选择另一个父选择器之后将子选择器返回到其第一位置,但是没有成功。 (请参见didSelectRow
下的>
您还有其他想法吗?
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return countries.count
} else if component == 1 {
let selectedCountry = pickerView.selectedRow(inComponent: 0)
return countries[selectedCountry].cities.count
} else {
let selectedCountry = pickerView.selectedRow(inComponent: 0)
let selectedCity = pickerView.selectedRow(inComponent: 1)
return countries[selectedCountry].cities[selectedCity].posts.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
return countries[row].name
} else if component == 1{
let selectedCountry = pickerView.selectedRow(inComponent: 0)
return countries[selectedCountry].cities[row].name
} else {
let selectedCountry = pickerView.selectedRow(inComponent: 0)
let selectedCity = pickerView.selectedRow(inComponent: 1)
return countries[selectedCountry].cities[selectedCity].posts[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
pickerView.reloadAllComponents()
if component == 0 {
pickerView.selectRow(0, inComponent: 1, animated: true)
pickerView.selectRow(0, inComponent: 2, animated: true)
} else if component == 1 {
pickerView.selectRow(0, inComponent: 2, animated: true)
}
}
我有一个PickerView,根据此代码包含3个组件。右边的两个选择器根据左边的先前选择更改其内容。不幸的是,当我更改...
当您在reloadAllComponents()
中调用didSelectRow
时,您尚未更新所选行,因此崩溃了。