Search code examples
swiftxcodeuipickerviewuisegmentedcontrolibaction

How set rows in PickerView after action on SegmentedControl


I'm new to Swift and Xcode and I want to set rows to a PickerView in relationship which Segment in SegmentedControl are selected. I tried the following to set the array firstInputUnitChooseData as rows for my PickerView firstInputUnitChoose:

class FirstViewController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var wantedInputProperty: UISegmentedControl!
    @IBOutlet weak var firstInputUnitChoose: UIPickerView!

    var wantedInputPropertyData: [String] = [String]()
    var firstInputUnitChooseData: [String] = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Connect data
        self.firstInputUnitChoose.delegate = self
        self.firstInputUnitChoose.dataSource = self

        wantedInputProperty.addTarget(self, action: #selector(FirstViewController.doSomething), for: .valueChanged)

    }

    @IBAction func doSomething() {
        let choosableFirstUnit = wantedInputProperty.titleForSegment(at: wantedInputProperty.selectedSegmentIndex)
        switch choosableFirstUnit {
        case "p", "p,h", "p,s", "p,t", "p,x", "p,\u{03C1}":
            firstInputUnitChooseData = ["Bar", "MPa", "Pa"]
        case "t", "t,x" :
            firstInputUnitChooseData = ["°C", "K"]
        case "h,s", "h,\u{03C1}":
            firstInputUnitChooseData = ["J/Kg", "kJ/Kg"]
        default:
            firstInputUnitChooseData = ["X"]
        }
    }

    // The number of columns of data
    func numberOfComponents(in pickerView: UIPickerView) -> Int {

        return 1
    }

    // Number of rows of data
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        return firstInputUnitChooseData.count
    }

    // The data to return for the row and component (column) that's being passed in
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        return firstInputUnitChooseData[row]
    }

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

        // Create action for selected PickerView row
    }

If I use print(chooseableFirstUnit) or print(firstInputUnitChooseData) inside the func DoSomething() it prints out the right data into the console.

for example: If I set the Array

firstInputUnitChooseData = ["Bar", "MPa", "Pa"]

directly inside func viewDidLoad() , it works, but that's not what I want.


Solution

  • You need to reload the pickerView , so at end of the function doSomething do

    self.firstInputUnitChoose.reloadAllComponents()