xcodeswiftuipickerview

How to use two UIPickerViews in one view controller?


I have two UIPickerControllers in one view controller. I can get one to work, but when I add a second, my app crashes. Here is the code I use for one picker view:

import UIKit

class RegisterJobPosition: UIViewController, UIPickerViewDelegate {

    @IBOutlet weak var positionLabel: UILabel!

    var position = ["Lifeguard", "Instructor", "Supervisor"]

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func numberOfComponentsInPickerView(PickerView: UIPickerView!) -> Int
    {
        return 1
    }

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

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

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {        
        positionLabel.text = position[row]
    }
}

Now, how can I get a second picker to work? Say my second picker view is called location (the other one is called position). I tried duplicating the code within the picker view methods for location but it doesn't work.


Solution

  • Based on the information I have in the question, I'd say that you need to set up the data source & delegate methods to handle the ability to distinguish between which picker instance is calling them.

    Using the tag property on the picker view is one strategy.

    There should be some if/else or switch statements in the methods that have varying logic depending on whether it's the location or the position picker that's being referenced.