How to give this picker view a datasource

Michael picture Michael · Mar 21, 2011 · Viewed 16.3k times · Source

Here I am adding a pickerview programaticly

 - (void)viewDidLoad {
        [super viewDidLoad];
        CGRect pickerFrame = CGRectMake(0,280,321,200);

        UIPickerView *myPickerView = [[UIPickerView alloc] init]; //Not sure if this is the proper allocation/initialization procedure

        //Set up the picker view as you need it

        //Set up the display frame
        myPickerView.frame = pickerFrame; //I recommend using IB just to get the proper width/height dimensions

        //Add the picker to the view
        [self.view addSubview:myPickerView];
    }

But now I need to actually have it display content and somehow find out when it changes and what value it has changed to. How do I do this?

Answer

pradeepa picture pradeepa · Mar 22, 2011

in .h file place this code

@interface RootVC : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>

assign the datasource and delegate to the picker

// this view controller is the data source and delegate
myPickerView.delegate = self;
myPickerView.dataSource = self;

use the following delegate and datasouce methods

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{

}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    return 200;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 50;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *returnStr = @"";
    if (pickerView == myPickerView)
    {       
        returnStr = [[levelPickerViewArray objectAtIndex:row] objectForKey:@"nodeContent"];
    }

    return returnStr;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (pickerView == myPickerView)
    {
        return [levelPickerViewArray count];
    }
}

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