Search code examples
iphoneobjective-cuipickerview

use two UIPickerView in the same class


I wrote this code for the first UIPickerView

- (void)viewDidLoad
     NSURL *url = [NSURL URLWithString:
                      @"http://localhost:8080/Data/resources/converter.country/"];
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
        [request setDelegate:self];
        [request startAsynchronous];
      //  countrys = [[UIPickerView alloc] init];
        countrys.delegate = self;
        countrys.dataSource = self;
        countrys.showsSelectionIndicator = YES;
        countryField.inputView=countrys;


     - (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
        NSString *codeCity;
        codeCity=[countriesArray objectAtIndex:row];
        return codeCity;
    }

    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
        return 1;
    }

    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
        return [countriesCodeArray count];
    }

And then i wanted to make another UIPickerView with cities . I wrote this

 citys.delegate = self;
    citys.dataSource = self;
    citys.showsSelectionIndicator = YES;
    cityField.inputView=citys;

But when i click on it i have countries list . How should i change the datasource ? And how to use the default function of the UIPickerView, like numberOfComponentsInPickerView , numberOfRowsInComponent: ... with the second UIPickerView ?


Solution

  • You can assign tag to your pickerviews and then can check these tags in datasource/delegate methods

    citysPickerview.tag = 2
    
    otherPickerview.tag = 1
    
    
    // then you can check for these tags in pickerview datasource/delegate methods like this - 
    
    - (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    
            NSString *title;
    
          if (pickerview.tag == 1) // this is otherPickerview
          {
              title=[countriesArray objectAtIndex:row]; // your logic to get title for otherpickerview
    
    
          }
          else if (pickerview.tag == 2) // this is citysPickerview
          {
             title=[countriesArray objectAtIndex:row]; // your logic to get title for cityspickerview
    
    
          }
    
      return title;
    
    }
    

    You should follow this same mechanism in your all datasource/delegate code :)