Search code examples
iphoneobjective-cuipickerviewuipicker

How to change the picker rows based on another picker's selection?


I have two pickers - country and region. I need to populate the region picker based on the row selected in the country picker. I have arrays to populate both the pickers. I need some help to change the rows of region picker based on the country picker's selection. Any help would be greatly appreciated. Thanks a lot in advance.


Solution

  • Ok You have two pickers lets say countryPicker and regionPicker.

    in the delegate method for UIPickerView add one condition

    - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
    { 
        NSString *pickerTitle = @"";
        if (pickerView == countryPicker)
        {
            pickerTitle =  [countryFeeds objectAtindex:row];
            //assigns the country title if pickerView is countryPicker
        }
        else if (pickerView == regionPicker)
        {
            pickerTitle =  [regionFeeds objectAtindex:row];
            //assigns the region title if pickerView is regionPicker
        }
    
        return pickerTitle;
    }
    - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
    {
        if (pickerView == countryPicker)
        {
            //selects the region corresponding to the selected country.
            //totalRegions is a NSDictionary having country names as keys and array of their regions as values
            regionFeeds = [totalRegions objectForKey:[countryFeeds objectAtindex:row]];
    
            //Now reloading the regionPicker with new values.
            [regionPicker reloadAllComponents];
        }
        else if (pickerView == regionPicker)
        {
            // your code to select a region
        }
    }
    

    I hope this solves your problem :)
    BR, Hari