Search code examples
iosuipickerview

UIPickerView spin second wheel when spinning the first one


I want to make 2-row picker for different arrays with the same number of elements and spin both wheels together: if I spin the first wheel, the second one spins with it and contrariwise. Could you please help me.

I've got 2 arrays, which I receive from parsing the data, let it be like:

self.streetTypeArray = @[@"street",@"square",@"park",@"alley"];
self.streetNameArray = @[@"Marx",@"Engels",@"Lenin",@"Ordzhonikidze"];

next:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    // returns the number of 'columns' to display.
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
   // for both components the same number of rows.
   return [self.streetTypeArray count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    // return array with data to picker components.
    if(component == 0) {
        return [self.streetTypeArray objectAtIndex:row];
    }

    else {
        return [self.streetNameArray objectAtIndex:row];
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
....
}

So I don't know how correctly spin the second component to the same row, when I spin the first one and contrariwise in didSelectRow method


Solution

  • From what I gathered from your requirement, I suppose you want to implement the - pickerView:didSelectRow:inComponent delegate method as following:

    -(void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
    {
        if(component == 0) //streetType
        {
            [pickerView selectRow:row inComponent:1 animated:YES];
        }
        else if(component == 1) //streetName
        {
            if(row != [pickerView selectedRowInComponent:0] )
            {
                [pickerView selectRow:[pickerView selectedRowInComponent:0] inComponent:1 animated:YES];
            }
        }   
    }