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 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.