更改组件0时,重置UIPickerView的第一个组件的值

时间:2019-04-28 19:27:07

标签: arrays swift uipickerview

我不知道如何在更改组件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

1 个答案:

答案 0 :(得分:1)

更改组件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
        }
    }
}