Shikha Sharma
Shikha Sharma

Reputation: 469

Populating second picker corresponding to the value selected in first picker view on same view

I want to use two picker views in same view where first picker view is of category and when a category is selected, its corresponding values are added to second picker view. How can I make it possible? Values are taken from JSON.

Upvotes: 0

Views: 103

Answers (2)

Himanth
Himanth

Reputation: 2421

You can get value selected in first picker view like this

NSInteger row;
NSArray *firstPickerViewDataArray;
UIPickerView *firstPickerView;
NSString *selectedValue;

row = [firstPickerView selectedRowInComponent:0];
selectedValue  = [firstPickerViewDataArray objectAtIndex:row];

Get the data from server or wherever you want and store that into another array like

NSArray * secondPickerViewDataArray;

After that you can use below method to show values

    - (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
        if (pickerView == secondPickerView){
          // Do whatever you want based on selected value in first PickerView
            return secondPickerViewDataArray[row];
            }else{
   //stuff for first pickerView
         }
            }

Upvotes: 1

Shayan Jalil
Shayan Jalil

Reputation: 588

This is fairly simple. You must be populating your second picker view from an array.

Make your view controller the delegate and data source for both the picker views.

Then when the 'func pickerView(UIPickerView, didSelectRow: Int, inComponent: Int)' delegate method is called when you select an item in the first picker view, update the data array for the second picker view and call reloadAllComponents on it

Here is some code

func pickerView(UIPickerView, didSelectRow: Int, inComponent: Int)
{
    if (pickerView == self.firstPicker)
    {
        //calculate your data array for the second picker here
        self.secondPickerView.reloadAllComponents()
    }
}

Upvotes: 4

Related Questions