dom999999 dom999999 - 13 days ago 6
Swift Question

How to use 2 UIPickerView's in one View Controller?

I have 2 UIPickerController's in one of View Controllers. 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()
// Do any additional setup after loading the view, typically from a nib.

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

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 controller to work? Say my second PickerView is called
location
(the other one is called
position
). I tried duplicating the code within the PickerView methods for
location
but it doesn't work.

I'm using Swift.

Answer

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.