Reputation: 1122
I'm building an application that inserts records into a database, and it pulls items from that database from lookup tables so it has the proper items in predefined fields. Obviously a picker is the best route for this method, but I'm running into a problem. There are 2 different pages with about 15 different pickers between the two of them. Now what I need to do is load the picker as it's popped up when the user selects the field.
All the online tutorials and examples I've found are using either the GUI editor to link a picker with a data source, or using one single data source for a picker in a separate file(which I'm not doing).
How do I go about loading an NSMutableArray into a picker when it's called?
Thanks!
Upvotes: 0
Views: 2515
Reputation: 8526
Have a data source and delegate class that implements all the required data source/delegate methods, that is defined as conforming to UIPickerViewDataSource
and UIPickerViewDelegate
and that has @property (retain, nonatomic) NSMutableArray *dataArray;
defined in the header. Make the data source/delegate class's methods (such as - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
) load the strings etc from dataArray
. Then when creating/changing the picker, do the following:
MyPickerSource *source = [[MyPickerSource alloc] init];
source.dataArray = [NSMutableArray arrayWithArray:<PreloadedArray>];
[picker setDelegate:source];
[picker setDataSource:source];
[picker reloadAllComponents]; // If re-using an old picker
[source release];
[self addSubview:picker]; // If creating a new picker
Hope this is all clear!
Upvotes: 3
Reputation: 17732
You want to use a UIPickerViewDataSource
and UIPickerViewDelegate
, and implement the necessary functions, namely numberOfRowsInComponent:
and titleForRow:
, through these methods you can draw the data from your NSMutableArray
.
The important thing to consider is for you to call reloadAllComponents
on the pickerview when you need it to update. You can also use selectRow: inComponent: animated:NO
to keep the picker scrolled to the appropriate selection when you update the components in the list.
Upvotes: 2