-2

I'm trying to add different uipickerviews to one view, the problem is that that the number of components is set one for all picker views:

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

Is it possible to set different number of components for different uipickerviews? The same question is for other functions, like number of rows

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int)

and source with the components themselves:

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int)

how can this distinguishing of uipickerviews be implemented in swift ?

Anton
  • 155
  • 13

1 Answers1

1

Create IBOutlets for your pickerViews and then check the pickerview in the function before returning the value

@IBOutlet weak var picker1: UIPickerView!
@IBOutlet weak var picker2: UIPickerView!

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    if pickerView == picker1 {
        return 2
    }
    else {
       return 1
    }
}

Edit: If you are creating your pickers programmatically, create properties for them

var picker1: UIPickerView?
var picker2: UIPickerView?

func createMyPickers() {
    picker1 = UIPickerView(...
    picker2 = UIPickerView(...
}

That way you can access your pickers in the delegate methods!

Rajeev Bhatia
  • 2,974
  • 1
  • 21
  • 29
  • thank you! this works, in my case had to use tag to distinguish multiple uipickerviews – Anton Oct 06 '17 at 12:20
  • DO NOT RELY ON TAGS!! Make IBOutlets – Rajeev Bhatia Oct 06 '17 at 12:24
  • I add this picker views programmatically to different subviews , so I can't use IBOutlets( clicked the green check mark is that marked as answer ? – Anton Oct 06 '17 at 12:38
  • Thanks! Also, in that case, just use properties. Will edit the answer. Apple strongly suggests against using tags and so do I since they can get quite tedious to manage – Rajeev Bhatia Oct 06 '17 at 12:43