1

I have read other questions about creating a UIPickerView with two or more columns but cannot find the exact solution.

How is this done for the iPhone programmatically? How do you add static data? Thanks!

john
  • 1,189
  • 2
  • 15
  • 20

3 Answers3

12

Make your controller (or whatever is controlling the behavior of the PickerView) support the UIPickerViewDelegate protocol. Then, implement:

- (int) numberOfColumnsInPickerView:(UIPickerView*)picker

to return the number of columns you want, and

- (int) pickerView:(UIPickerView*)picker numberOfRowsInColumn:(int)col

to return the number of rows for each column, and finally:

- (UIPickerTableCell*) pickerView:(UIPickerView*)picker tableCellForRow:(int)row inColumn:(int)col

to setup each cell.

See the reference for UIPickerView and UIPickerViewDelegate.

Dejell
  • 13,947
  • 40
  • 146
  • 229
zpasternack
  • 17,838
  • 2
  • 63
  • 81
2

There is an excellent tutorial on this subject here.

Spinoxa
  • 657
  • 2
  • 7
  • 23
0

Assuming you have a dictionary or a couple of arrays holding your static data. For simplicity I will go with a very simple array.

You have to modify your view controllers interface definition to tell the program that your view controller can provide data and delegation to a picker view.

@interface NVHomeViewController : UIViewController <UIPickerViewDelegate,UIPickerViewDataSource>

Than just implementing a couple of methods will make it work however documentation should be checked for other methods that are optional but provides more customization and control.

@interface NVHomeViewController : UIViewController <UIPickerViewDelegate,UIPickerViewDataSource>

NSArray *options;
- (void)viewDidLoad
{
    [super viewDidLoad];
    options = @[@"a",@"b",@"c",@"d"];
}

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

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [options count];
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [options objectAtIndex:row];
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSLog(@"%@ selected.",[options objectAtIndex:row]);
}
Gorky
  • 1,393
  • 19
  • 21