gpt4 book ai didi

arrays - 当组件 0 更改时重置 UIPickerView 第一个组件的值

转载 作者:行者123 更新时间:2023-11-28 13:41:58 28 4
gpt4 key购买 nike

我不知道如何在组件 0 更改时将 PickerView 的第一个组件中使用的数组重置为组件 0(为了避免由于 indexOutOfRange 可能导致的错误)。

这是我的数据结构

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]
}
}

现在,当我(比方说)在 banana2 和 cherry3 中,但我切换到 banana1 时,我得到一个 indexOutOfRange 错误,因为第一个香蕉数组当然没有第三个项目。每当香蕉行更改为将樱桃行重置为 0 时,我都希望如此。

__________ 更新 ____________这是我发现的导致崩溃的另一个错误 (indexOutOfRange),我发布了一个屏幕截图。

Image causing Crash

最佳答案

当组件 0 更改时,将组件 1 中的选定行设置为 0。

此外,无需重新加载所有组件。只有组件 1 需要重新加载。

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)
}

对于第二次崩溃,尝试一些防御性编程来避免崩溃:

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
}
}
}

关于arrays - 当组件 0 更改时重置 UIPickerView 第一个组件的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55893829/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com