开发者

one picker, multiple arrays for datasources - working fine but how?

I h开发者_JAVA技巧ave a class with 4 arrays: tab_1,tab_2,tab_3 and tab_T. I set the picker's delegate and datasource to self (which is the class containing the arrays).

The picker is called when textfields begin editing. I return NO in order to prevent the keyboard from being shown. I have a method animating the picker instead.

Depending on which textfield is touched i do: tab_T=tab_1; or 2 or 3

In my opinion this assignment makes tab_T the datasource of the picker. Is this assignment really binding the array tab_T to the datasource? Is there a way to manually assign it? i'm sure there is. But picker.datasource=tab_1 doesn't work. i got a " warning: class 'NSMutableArray' does not implement the 'UIPickerViewDataSource' protocol".

Its my first app maybe i am forgetting a step i did at the early ages of my app.

Looking forward to anyone willing to help.

Wallou


A UIPickerView's datasource has to be a class that implements the UIPickerViewDataSource protocol. The populating of the picker view is done in these two methods:

– numberOfComponentsInPickerView:  
– pickerView:numberOfRowsInComponent: 

Since NSArray doesn't implement the protocol using:

pickerView.datasource=someArray;

... generates the error you've seen saying the array does not implement the protocol.

The first thing you need to do is to declare that your controller implements the protocol like so:

@interface MyControllerClass: UIViewController <UIPickerViewDataSource,UIPickerViewDelegate> 

then you need to implement the protocol's methods which will look something like:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1; //or whatever
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [self.tab_T count]; // assuming just one component
}

To actually populate the components, you need the UIPickerViewDelegate methods. (I know it seems that the datasource should provide, you know, data but for some reason they have it backwards.)

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [self.tab_T objectAtIndex:row]; //assuming one component
}

The key idea here is that the objects that implement the datasource and delegate methods serve as the interface between the picker and whatever data structure actually holds the data. In this case, its just simple arrays but it could be anything including Core Data, SQL or downloaded from a URL.

The pickerview never directly deals with the data structure at all. It's always the object/s that implement the datasource and delegate methods that do the interaction.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜