Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add multiple components to a PickerView?

It may be a simple question but how do I add multiple components to a UIPickerView? I use NSMutableArray to populate one component but I dont know how to populate the others. I also need to change the value of a label when a row is selected. Thanks in advance Kieran

like image 414
knw500 Avatar asked Dec 09 '25 22:12

knw500


2 Answers

I take it that you are a beginner. Here's how to implement the methods nacho has rightly pointed out:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    // return the number of components required
    return 2;
}

You can use other NSMutableArray's to populate the components. Assuming that you have 2 components, each using different NSMutableArray i.e. array1 and array2:

// Return row count for each of the components
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return [array1 count];
    }
    else {
        return [array2 count];
    }
}

// Populate the rows of the Picker
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {

    // Component 0 should load the array1 values, Component 1 will have the array2 values
    if (component == 0) {
        return [array1 objectAtIndex:row];
    }
    else if (component == 1) {
        return [array2 objectAtIndex:row];
    }
    return nil;
}

Use this code to change the text of a label, say selectedValue when a value is selected in the PickerView:

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    selectedValue.text = [NSString stringWithFormat: @"%@, %@", [array1 objectAtIndex:[myPicker selectedRowInComponent:0]],[array2 objectAtIndex:[myPicker selectedRowInComponent:1]]];
}

... and you are good to go :)

You might also want to see http://joshhighland.com/blog/2009/09/17/uipickerview-spinning-multiple-components/ for valuable tips on pickerView programming.

like image 198
Tiquelou Avatar answered Dec 12 '25 14:12

Tiquelou


You need to set the datasource and use

– numberOfComponentsInPickerView:
– pickerView:numberOfRowsInComponent:

set its delegate and use:

– pickerView:didSelectRow:inComponent:

to change your label when a certain row in a certain component is selected. Very likely to UITableViewDelegate and Datasource

and also taking a glance to documentation helps :)

like image 26
nacho4d Avatar answered Dec 12 '25 12:12

nacho4d