How would I set up a UIPickerView?

Nikita Jerschow picture Nikita Jerschow · Dec 7, 2012 · Viewed 45k times · Source

I am setting up a UIPickerView to have choices like choice a, choice b, choice c and so on. I have tried to interpret the sample code from Apple but that seems very difficult to understand for a beginner like me. I also would like the choices from the picker view to take me to another page if that is possible.

Answer

Mohit_Jaiswal picture Mohit_Jaiswal · Dec 7, 2012

It's obvious for every beginner that it is some what tedious to understand these things the first time.

Anyways, do you know how to use UITableViews? Do you know how to use UITableViewDelegate and UITableViewDataSource? If your answer is yes, then just imagine UIPickerViews are like UITableViews (but remember they are not UITableViewControllers).

Let's say, I've a UIPickerView:

UIPickerView *objPickerView = [UIPickerView new];  // You need to set frame or other properties and add to your view...you can either use XIB code...

1) First you need to assign the delegate and dataSource to the UIPickerView either via IB or code. It depends on your implementation (So this step looks very similar to a UITableView, doesn't it?)

Like this:

objPickerView.delegate = self; // Also, can be done from IB, if you're using
objPickerView.dataSource = self;// Also, can be done from IB, if you're using

2) Next, you need to define number of sections, like this:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
     return 1;  // Or return whatever as you intend
}

2) Then you need to define the number of rows you need:

- (NSInteger)pickerView:(UIPickerView *)thePickerView 
numberOfRowsInComponent:(NSInteger)component {
     return 3;//Or, return as suitable for you...normally we use array for dynamic
}

3) Then, define title for row (And if you have multiple section, then title for each section):

- (NSString *)pickerView:(UIPickerView *)thePickerView 
             titleForRow:(NSInteger)row forComponent:(NSInteger)component {
     return [NSString stringWithFormat:@"Choice-%d",row];//Or, your suitable title; like Choice-a, etc.
}

4) Next, you need to get the event when someone clicks on an element (As you want to navigate to other controller/screen):

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

//Here, like the table view you can get the each section of each row if you've multiple sections
     NSLog(@"Selected Color: %@. Index of selected color: %i", 
     [arrayColors objectAtIndex:row], row);

     //Now, if you want to navigate then;
     // Say, OtherViewController is the controller, where you want to navigate:
     OtherViewController *objOtherViewController = [OtherViewController new];
     [self.navigationController pushViewController:objOtherViewController animated:YES];

}

That's all the implementation you need.