在一个UIPickerView中使用两个数组

时间:2018-11-02 22:56:45

标签: swift uipickerview

我想在pickerview中显示两个数组。

当用户单击第一个按钮时,选择器将显示第一个数组 和第二个按钮相同。

代码是:

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

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if currentButtonTag == 1 {
        return pickerData.count
    } else if currentButtonTag == 2 {
        return 2
    }
    return 2
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if currentButtonTag == 1 {
        return pickerData[row]
    } else if (currentButtonTag == 2) && (currentCity == "بغداد") {
        return baghdad[row]
    }
    return other[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    currentCity = pickerData[row]
}

@IBAction func showw(_ sender: Any) {
    currentButtonTag = cityButton.tag
    showView.center = CGPoint(x: view.frame.size.width  / 2,
                                 y: view.frame.size.height - ( showView.frame.size.height / 2) )

    showView.transform = CGAffineTransform.init(scaleX: 0.3, y: 0.3)
    UIView.animate(withDuration: 0.4) {
        self.showView.alpha = 1
        self.showView.transform = CGAffineTransform.identity

    }
    view.addSubview(showView)
}

@IBAction func ShowSide(_ sender: Any) {
    currentButtonTag = sideButton.tag

    view.addSubview(showView)
    showView.center = CGPoint(x: view.frame.size.width  / 2,
                              y: view.frame.size.height - ( showView.frame.size.height / 2) )

    showView.transform = CGAffineTransform.init(scaleX: 0.3, y: 0.3)
    UIView.animate(withDuration: 0.4) {
        self.showView.alpha = 1
        self.showView.transform = CGAffineTransform.identity
    }
}

单击错误索引超出范围的第二个按钮时,应用程序崩溃。

1 个答案:

答案 0 :(得分:0)

更改标签后,您需要重新加载pickerView

currentButtonTag = cityButton.tag
pickerView.reloadAllComponents()