Search code examples
swiftuipickerview

UI picker view error I try to get it to populate models,


I am trying to get the second picker to display the array I created, but it won't and I have been messing with it for hours. Any ideas?

    class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

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

     return aircraft.count
}


@IBOutlet weak var aircraftType: UIPickerView!
@IBOutlet weak var model: UIPickerView!


let aircraft = ["Airbus", "Boeing", "Bombardier", "Embraer"]
let models = [ "Airbus": ["A300", "A320", "A330", "A350", "A380"], "Boeing": ["737", "747", "757/767", "777", "787"], "Bombardier": ["CRJ200", "CRJ700/900"], "Embraer": ["ERJ145", "ERJ170", "ERJ190"] ]



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

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

}


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

Solution

  • Please find the updated code. You should reload pickerview component on select of Aircrafts. Do please take of optional bindings

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
                if component == 0 {
                    return aircraft.count
                }
                else {
                    return (models[aircraft[aircraftType.selectedRow(inComponent: 0)]]?.count)!
                }
            }
    
        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return 2
        }
    
        func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            if component == 0 {
                return aircraft [row]
            }
            else {
                return models[aircraft[aircraftType.selectedRow(inComponent: 0)]]?[row]
            }
        }
    
    
        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            if component == 0 {
                aircraftType.reloadComponent(1)
            }
        }