Search code examples
iosswiftuibuttonintuipickerview

Add button to UIPickerView to go to next number


I have 3 columns on my pickerView and its representing a 3-digit number. Is there any function I can add to a UIButton that makes the wheel go round? For example, when it's showing "119", with a press of the UIButton, it should go to "120". Here's what I have so far:

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)"
}

Solution

  • Here is your code, simplified. buttonPressed will cause pickerView to go to the next number. When it reaches 999, it turns back to 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))"
        }
    }