1

I have several UIPickerView's on the same view. When I select one item in the first UIPickerView, I want to load data to the other UIPickerView's depending on the selected item.

Example: When I select France as a country, I should get cities on the city picker (Paris, Toulouse, etc).

How could I implement methods to do that?

iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
M Merou
  • 13
  • 2

2 Answers2

0

Once your first UIPickerView has been used, you can load the data into the others and call:

[thePicker reloadAllComponents];
sangony
  • 11,636
  • 4
  • 39
  • 55
0

If you have references to each picker view, then you'd just do something like this

// These are instance variables within the view controller
NSString *selectedCountry;
NSArray *listOfCountries = @[@"France", @"Switzerland"];

// In the picker view delegate callback
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (pickerView == countryPickerView) {
        selectedCountry = [listOfCountries objectAtIndex:row];
        [cityPickerView reloadAllComponents]; // Or you can reload individual components
    }
}

The cityPickerView's datasource should be looking for what the value of selectedCountry is and populating itself with cities for that given country.


As a side note, if you have multiple picker views within a single view, you may want to consider creating a subclass for each UIPickerView and making the subclass the delegate/datasource for each pickerview so you don't end up with spaghetti code and having to check if (pickerView == countryPickerView) like in this example.

iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
  • Thank you so much for your response , In my programm I have one function that take as parameter a country and return list of cities related to this country .so Where should I call this function exactlly , What I assum is I get the list of countries in viewdidload , but the list of cities I don't know where shoud I call it and use " reloadcomponents" .Excuse me , I am new at objectiv-C developement. – M Merou May 01 '13 at 22:44
  • @MarouaneMouyarden You should use the UIPickerViewDelegate methods for this. One is: `- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component`. The entire class is here: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIPickerViewDelegate_Protocol/Reference/UIPickerViewDelegate.html – iwasrobbed May 01 '13 at 22:59
  • You'll have to get used to reading those class references to see what methods and properties are available for you to use with all the different controls and classes available on iOS. – iwasrobbed May 01 '13 at 23:00
  • 1
    @MarouaneMouyarden If my answer helped you, please consider pressing the checkmark next to it so this question gets closed out. – iwasrobbed May 02 '13 at 13:30