Search code examples
iphoneiosuipickerview

Setting data for multiple UIPickerView


I have two UIPickerViews With data being pulled from an array though I can't seem to program them separately. Here is the code that I am using for my UIPickerViews:

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

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

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
      return[[treatments objectAtIndex:row]valueForKey:@"treatmentName"];
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    _buttonText.text = [[treatments objectAtIndex:row]valueForKey:@"treatmentName"];
    if (![_buttonText.text isEqual: @"Pick a Treatment Name"]) {
        _buttonText.textColor = [UIColor blackColor];
    }
}

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

- (NSString *)nursePicker:(UIPickerView *)nursePicker titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return[[nurses objectAtIndex:row]valueForKey:@"nurseName"];
}

When I run the code the pickers show the same data

Thanks in advance


Solution

  • Store a reference to your two picker views and use the UIPickerView that is passed as an argument to the datasource methods in order to determine which picker view you are using.

    -(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
        if (pickerView == self.nursePicker) {
            return [nurses count];
        }
        else if (pickerView == self.treatmentPicker) {
            return [treatments count];
        }
    }
    

    Same idea for every datasource method