PickerView的selectRow如何影响启用按钮?

时间:2019-05-30 11:50:15

标签: swift uipickerview

我有UIPickerView和按钮。我想如果我选择原始数字0,那么按钮未启用,反之亦然。我的代码中有这个构造:

    import UIKit

    class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    ...
    @IBOutlet weak var buttonOutlet: UIButton!
    @IBOutlet weak var firstPicker: UIPickerView!
    @IBOutlet weak var secondPicker: UIPickerView!

    let firstData = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10"]
    let secondData = ["00", "10", "20", "30", "40", "50"]

    @IBOutlet weak var firstLabel: UILabel!
    @IBOutlet weak var secondLabel: UILabel!

    var first: Int!
    var second: Int!

    var firstRaw = 1
    var secondRaw = 0
            ...
        override func viewDidLoad() {
            super.viewDidLoad()

            self.firstPicker.delegate = self
            self.firstPicker.dataSource = self
            self.secondPicker.delegate = self
            self.secondPicker.dataSource = self

            firstPicker.selectRow(firstRaw, inComponent: 0, animated: true)
            secondPicker.selectRow(firstRaw, inComponent: 0, animated: true)
            if (self.firstRaw == 0) && (self.secondRaw == 0) {
                self.buttonOutlet.isEnabled = false
            } else {
                self.buttonOutlet.isEnabled = true
            }
        ...
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            if pickerView == firstPicker {
                ...
            } else {
                ...
    }

为什么这种构造不起作用?

1 个答案:

答案 0 :(得分:0)

要检测何时选择了值,您必须实现UIPickerViewDelegate,还必须实现选择器视图的didSelectRow方法。我假设您已经填充了选择器视图数据。

class ViewController : UIViewController, UIPickerViewDelegate {

    @IBOutlet weak var buttonOutlet: UIButton!
    @IBOutlet weak var firstPicker: UIPickerView!
    var firstRaw = 1
        ...
    override func viewDidLoad() {
        super.viewDidLoad()
        self.firstPicker.delegate = self
        ...
    }
    func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int){
        if self.firstRaw == 0 {
            self.buttonOutlet.isEnabled = false
        } else {
            self.buttonOutlet.isEnabled = true
        } 
    }
}