如何在对 SegmentedControl 执行操作后在 PickerView 中设置行

How set rows in PickerView after action on SegmentedControl

我是 Swift 和 Xcode 的新手,我想将行设置为关系中的 PickerView,其中选择了 SegmentedControl 中的 Segment。我尝试了以下方法将数组 firstInputUnitChooseData 设置为我的 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
    }

如果我在 func DoSomething() 中使用 print(chooseableFirstUnit)print(firstInputUnitChooseData),它会在控制台中打印出正确的数据。

例如:如果我设置数组

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

直接在 func viewDidLoad() 里面,它可以工作,但这不是我想要的。

您需要重新加载 pickerView ,所以在函数结束时 doSomething 执行

self.firstInputUnitChoose.reloadAllComponents()