Show data in UIPickerView second component based on first component selection

前端 未结 4 513
悲哀的现实
悲哀的现实 2020-12-06 08:42

I am using a picker with two components. I want if I select a row in first component on the basis of selected component it shows the value of the corresponding data.

4条回答
  •  时光说笑
    2020-12-06 08:57

    Usually you do it like that. You create a plist file containing the data of all your countries the result is something like

    
    
    
      
        England
        
            Chelsea
            Arsenal
        
        Spain
        
            Barca
            Real
        
     
    
    

    assuming the following are defined in the properties or somewhere

    NSDictionary *countryClubs;
    NSArray *countries;
    NSArray *clubs;
    

    you then do things like that

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        NSBundle *bundle = [NSBundle mainBundle];
        NSURL *plistFile = [bundle URLForResource:@"myPListFile" withExtension:@"plist"];
        NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfURL:plistFile];
        self.countryClubs = dictionary;
    
        NSString *selectedCountry = [self.countries objectAtIndex:0];
        NSArray *array = [countryClubs objectForKey:selectedCountry];
        self.clubs = array;
    }
    
    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
        return 2;
    }
    
    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
        if (component == 0)
            return [self.countries count];
        return [self.clubs count];
    }
    
    - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row
            forComponent:(NSInteger)component {
        if (component == 0)
            return [self.countries objectAtIndex:row];
        return [self.clubs objectAtIndex:row];
    }
    
    - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
           inComponent:(NSInteger)component {
           if (component == 0) {
             NSString *selectedCountry = [self.countries objectAtIndex:row];
             NSArray *array = [countryClubs objectForKey:selectedCountry];
             self.clubs = array;
             [picker selectRow:0 inComponent:1 animated:YES];
             [picker reloadComponent:1];
        }
    }
    

    This should help you. I hope there is not to much typo mistakes but you should at least get the general idea.

提交回复
热议问题