我觉得我很接近,因为下面的代码适用于静态uipickerview,但我正在尝试根据第一个选择动态设置pickerview,尽管我查看了教程和搜索,但仍无法完全理解这一点。例如,如果在myPickerData中选择“Brown”,则myPickerData中只应显示“本科生”;如果选择“达特茅斯”,则只应显示“本科生”和“MBA”;最后,如果选择“哥伦比亚”或“哈佛”,则显示“本科生”、“JD”、“MBA”。

var myPickerData = ["Select Your Dream College", “Brown", "Columbia", “Dartmouth”,  "Harvard" ]

var myPickerData2 = ["Undergraduate", "JD", "MBA"]

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 2
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    if component == 0 {
        return myPickerData.count
    }

    return myPickerData2.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

    if component == 0 {
        return myPickerData[row] as String
    }
    return myPickerData2[row] as String
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    uniSelected = myPickerData[pickerView.selectedRow(inComponent: 0)]

    collegeSelected = myPickerData2[pickerView.selectedRow(inComponent: 1)]
}

最佳答案

你可以试试

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

     if component == 0 {

         let str = myPickerData[row]

         if str == "Brown" {

            myPickerData2 = ["Undergraduate"]
         }
         else if str == "Dartmouth" {

            myPickerData2 = ["Undergraduate", "MBA"]
         }
         else {

            myPickerData2 = ["Undergraduate", "JD", "MBA"]

         }

         pickerView.reloadComponent(1)

      }
      else {

         uniSelected = myPickerData[pickerView.selectedRow(inComponent: 0)]

         collegeSelected = myPickerData2[pickerView.selectedRow(inComponent: 1)]
      }

}

//
这可能包含重复项,但您可以尝试
let mainDic:[String:[String]] = ["Select Your Dream College":[],
                 "Brown":["Undergraduate"],
                 "Dartmouth":["Undergraduate", "MBA"],
                 "Columbia":  ["Undergraduate", "JD", "MBA"],
                 "Harvard",["Undergraduate", "JD", "MBA"]]

那么
myPickerData2 = mainDic[myPickerData[row]]!

pickerView.reloadComponent(1)

在组件0中使用
myPickerData = Array(mainDic.keys)

将数据源设为mainDic并将键处理为myPickerData,将当前选定键的值处理为myPickerData2
编辑:在viewDidLoad
myPickerData = Array(mainDic.keys)
myPickerData2 = mainDic["Select Your Dream College"]! // it's default or simply []

09-27 21:59