How do I setup a second component with a UIPickerView

Dan Beaulieu picture Dan Beaulieu · Apr 14, 2015 · Viewed 9.9k times · Source

I've found some similar questions to this but none of the solutions matched my situation, and most were in objective-c which I don't know.

I'm trying to create a timer with minutes and seconds but I can't figure out how to wire up my second component.

How do I set up a second component with a UIPickerView?

This is what I have so far:

enter image description here

TimeViewController.swift

class TimeViewController: UIViewController, UIPickerViewDelegate {

    @IBOutlet weak var timeSegueLabel: UILabel!

    let minutes = Array(0...9)
    let seconds = Array(0...59)

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {

        return 2
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        return minutes.count

    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {

        return String(minutes[row])

    }

    override func viewDidLoad() {
        super.viewDidLoad()

    }
}

Answer

Dan Beaulieu picture Dan Beaulieu · Apr 14, 2015

Thanks to @Bluehound for pointing me in the right direction. I had to look at some objective-c on GitHub to find out exactly how to do it, this is the answer I was looking for:

TimeViewController:

class TimeViewController: UIViewController, UIPickerViewDelegate {

    @IBOutlet weak var timeSegueLabel: UILabel!

    let minutes = Array(0...9)
    let seconds = Array(0...59)

    var recievedString: String = ""

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {

        return 2

    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        //row = [repeatPickerView selectedRowInComponent:0];
        var row = pickerView.selectedRowInComponent(0)
        println("this is the pickerView\(row)")

        if component == 0 {
            return minutes.count
        }

        else {
            return seconds.count
        }

    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {

        if component == 0 {
        return String(minutes[row])
        } else {

        return String(seconds[row])
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        timeSegueLabel.text = recievedString

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

This is the result:

enter image description here