问题
I can't figure out how to reset to component 0 the array used in the first component of the PickerView, when component 0 is changed (in order to avoid possible errors due to indexOutOfRange).
This is the structure of my data
let bananas = ["banana1", "banana2"]
let fruitArray = ["banana1" : ["cherry1","cherry2"], "banana2" : ["cherry1", "cherry2", "cherry3"]]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return bananas.count
}
else {
let selectedBanana = pickerView.selectedRow(inComponent: 0)
return fruitArray[banana[selectedBanana]]!.count
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let selectedBanana = pickerView.selectedRow(inComponent: 0)
let selectedCherry = pickerView.selectedRow(inComponent: 1)
bananaPicked = bananas[selectedBanana]
cherryPicked = fruitArray[bananaPicked]![selectedCherry]
pickerView.reloadAllComponents()
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
return bananas[row]
}
else {
let selectedBanana = pickerView.selectedRow(inComponent: 0)
return fruitArray[selectedBanana]![row]
}
}
Right now when I'm (let's say) in banana2 and cherry3, but I switch to banana1, I get an indexOutOfRange error, because of course the first banana array does not have a third item. My wish it whenever the banana row is changed to reset to 0 the cherry row.
__________ UPDATE ______________ This is another error cause the crashing that I found (indexOutOfRange), I posted a screenshot.
回答1:
Set the selected row to 0 in component 1 when component 0 is changed.
Also, there is no need to reload all of the components. Only component 1 needs reloading.
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == 0 {
pickerView.selectRow(0, inComponent: 1, animated: false)
}
let selectedBanana = pickerView.selectedRow(inComponent: 0)
let selectedCherry = pickerView.selectedRow(inComponent: 1)
bananaPicked = bananas[selectedBanana]
cherryPicked = fruitArray[bananaPicked]![selectedCherry]
//pickerView.reloadAllComponents()
pickerView.reloadComponent(1)
}
For your second crash, try some defensive programming to avoid the crash:
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
return bananas[row]
}
else {
let selectedBanana = pickerView.selectedRow(inComponent: 0)
let rowData = fruitArray[bananas[selectedBanana]]!
if rowData.indices.contains(row) {
return rowData[row]
} else {
return nil
}
}
}
来源:https://stackoverflow.com/questions/55893829/reset-the-value-of-the-1st-component-of-uipickerview-when-component-0-is-changed