Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple PickerViews in one View?

I want to create 2 separate pickers in the same view using the same viewController. But how do I set separate delegates and datasource for them?

Can't seem to get it working. They show up with the same data. If you have any sample code on this it will be much appreciated.

Thanks.

like image 239
CC. Avatar asked Apr 20 '09 11:04

CC.


2 Answers

Note that each method of both the datasource and the delegate protocols contain a UIPickerView * parameter, for instance:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView

You need to use it to distinguish between your two instances, as follows:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{

    if([pickerView isEqual: pickerOne]){
      // return the appropriate number of components, for instance
         return 3;
    }

    if([pickerView isEqual: pickerTwo]){
      // return the appropriate number of components, for instance
         return 4;
    }
}
like image 118
Massimo Cafaro Avatar answered Nov 16 '22 06:11

Massimo Cafaro


The most straight forward way to do this is to use the tag property of the pickerView. I usually define these in the header for readability. You can set the tag in Interface Builder or in code.

#define kPickerOne 0
#define kPickerTwo 1

Then in your implementation file...

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView 
{
     if(pickerView.tag == kPickerOne)
     {
          // do something with picker one
     }
     else if(pickerView.tag == kPickerTwo)
     {
          // the other picker
     }
}
like image 15
Jab Avatar answered Nov 16 '22 08:11

Jab