Abhishek Dave Abhishek Dave - 7 days ago 6
Swift Question

Make UIPickerView dependent on selected row (Swift)

This is something I want to achieve
enter image description here

Make Second

UIPickerView
depend on currently selected row
enter image description here

Answer

Please check UIPickerViewDelegate and UIPickerViewDataSource: https://developer.apple.com/reference/uikit/uipickerviewdelegate https://developer.apple.com/reference/uikit/uipickerviewdatasource

The idea is:

  1. You configure the data of picker2 based on selected row of picker1.

  2. And whenever user selects a row in the picker1 reload the data in picker2

Code below:

class ViewController: UIViewController {

    @IBOutlet weak var picker1: UIPickerView!
    @IBOutlet weak var picker2: UIPickerView!

    let picker1Options = ["TV", "RADIO"]
    let picker2TVOptions = ["ABC", "SBS"]
    let picker2RadioOptions = ["TripleJ", "107.0", "CBS"]

    override func viewDidLoad() {
        super.viewDidLoad()
        self.picker1.dataSource = self
        self.picker1.delegate = self

        self.picker2.dataSource = self
        self.picker2.delegate = self
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

And,

extension ViewController: UIPickerViewDataSource, UIPickerViewDelegate
{
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if pickerView == self.picker1 {
            return picker1Options.count
        } else if picker1.selectedRow(inComponent: 0) == 0 {
            return picker2TVOptions.count
        }
        else if picker1.selectedRow(inComponent: 0) == 1 {
            return picker2RadioOptions.count
        }
        return 0
    }
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView == picker1 {
            return picker1Options[row]
        } else if picker1.selectedRow(inComponent: 0) == 0 {
            return picker2TVOptions[row]
        }
        else if picker1.selectedRow(inComponent: 0) == 1 {
            return picker2RadioOptions[row]
        }
        return nil
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if pickerView == picker1 {
            picker2.reloadAllComponents()
        }
    }
}