将按钮添加到 UIPickerView 以转到下一个数字

Add button to UIPickerView to go to next number

我的 pickerView 上有 3 列,它代表一个 3 位数。有没有我可以添加到 UIButton 的函数来使轮子转动?例如,当它显示“119”时,按 UIButton,它应该转到“120”。这是我目前所拥有的:

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

@IBOutlet weak var label: UILabel!
@IBOutlet weak var pickerView: UIPickerView!

let numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]

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

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return numbers[row]
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return numbers.count
}

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

    let val1 = numbers[pickerView.selectedRow(inComponent: 0)]
    let val2 = numbers[pickerView.selectedRow(inComponent: 1)]
    let val3 = numbers[pickerView.selectedRow(inComponent: 2)]

    label.text = "\(val1) \(val2) \(val3)"
}

当然,使用 selectRow 方法,该方法将 select 特定列(也称为组件)的一行。该方法还可以选择动画显示此更改。向故事板添加一个按钮并将其连接到如下方法:

@IBAction func go120(_ sender: Any) {
  pickerView.selectRow(1, inComponent: 0, animated: true)
  pickerView.selectRow(2, inComponent: 1, animated: true)
  pickerView.selectRow(0, inComponent: 2, animated: true)  
}

这是您的代码,已简化。 buttonPressed 将导致 pickerView 转到下一个数字。当达到999时,又变回000。

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var pickerView: UIPickerView!

    override func viewDidLoad() {
        super.viewDidLoad()

        changeLabelText()
    }

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

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return "\(row)"
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return 10
    }

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

    fileprivate func num(_ i: Int) -> Int {
        return pickerView.selectedRow(inComponent: i)
    }

    @IBAction func buttonPressed() {
        let currentNum = num(0) * 100 + num(1) * 10 + num(2)
        let nextNum = currentNum + 1

        pickerView.selectRow(nextNum % 1000 / 100, inComponent: 0, animated: true)
        pickerView.selectRow(nextNum % 100 / 10, inComponent: 1, animated: true)
        pickerView.selectRow(nextNum % 10, inComponent: 2, animated: true)

        changeLabelText()
    }

    fileprivate func changeLabelText() {
        label.text = "\(num(0)) \(num(1)) \(num(2))"
    }
}