How To Implement Single Component Picker In iPhone?

Let’s look at using pickers that let the user select from a list values. In this example we are going to create an NSArray to hold the values we want to display in the picker.

Step 1: Create a new project from Xcode and select view-base application template.

Step 2: Adding the following code to the controller Header file.


#import <uikit/UIKit.h>

@interface SingleComponentPickerViewController : UIViewController

IBOutlet UIPickerView *singlePicker;
NSArray *pickerData;

@property(nonatomic , retain) UIPickerView *singlePicker;
@property(nonatomic , retain) NSArray *pickerData;




Step 3: Double click .xib file and open it to interface Builder. Add a picker and a button to te View,and  then make the necessary connections. Control drag File’s Owner to the picker view,and select singlePicker outlet. Then single click the picker, bring up connection inspector, you’ll see that the first two items are DataSource and Delegate. Drag from the circle next to DataSource to the File’s Owner icon. Do it once again, and connect Delegate to File’s Owner icon. Next drag a Round Rect Button to the view, double-click it, give it a title of Select. Connect to Touch Up Inside to File’s Owner  and select buttonPressed action. Save the nib, and go back to Xcode.

Step 4: To make our controller work properly as the picker’s datasource and delegate, we are going to implement a few methods in the controller class:


NSInteger row = [singlePicker selectedRowInComponent:0];
NSString *selected = [pickerData objectAtIndex:row];
NSString *title = [[NSString alloc] initWithFormat:
@"you selected %@!", selected];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message : @"Thank you for choosing."
cancelButtonTitle :@"You are Welcome"
otherButtonTitles :nil];
[alert show];
[alert release];
[title release];

- (void)viewDidLoad {
NSArray *array = [[NSArray alloc] initWithObjects:@"Luke",@"Leia",@"Han",@"Chewbacca",@"Artoo",
self.pickerData = array;
[array release];
[super viewDidLoad];

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

-(NSInteger)pickerView:(UIPickerView *)pickerView
return [pickerData count];

-(NSString *)pickerView:(UIPickerView *)pickerView
return[pickerData objectAtIndex:row];



Step 5: Now compile and run your application on simulator.(See figure 1)

Figure 1: A picker displaying single list of values.

You can downloaded SourceCode from here SingleComponentPicker 2