How to Use Picker Views for iOS Apps - dummies

How to Use Picker Views for iOS Apps

By Rajiv Ramnath

In iOS applications, a picker view is a compact and visually appealing way to present a range of values in one or more dimensions to users (such as a date, where the dimensions are month, day, and year) and to let them select a set of values, with one value from each range.

The base class for a picker view is UIPicker. Pickers that are built from the base class need two delegates: one to implement the UIPickerViewDelegate protocol to provide the data shown on the picker and handle user interactions, such as the delegate for the Alert view; and another one, known as a data source delegate, to provide the dimensions of the picker (the number of columns and rows).

Despite its name, data source delegate protocol isn’t the protocol for actually providing the data. Instead, to provide the data for the picker, the delegate must implement the UIPickerViewDataSource protocol.

Below is a subclass of UIPicker, named UIDatePicker, which has the data source and view delegate already so complete that you can use a date picker almost like a text field. To see how the date picker is used, look at the User Detail view controller (TTTUserDetailViewController.m and .h).

The picture below shows the screen for the view managed by the User Detail view controller.

Preview of the user details page in an app.

The interface file has an outlet for the birthday date picker, as shown here:

@property (nonatomic, retain) IBOutlet UIDatePicker *birthdayPicker;

In the implementation file, you see the following:

 - (IBAction) saveChanges:(id)sender{
  NSDate *birthday = [self.birthdayPicker date];
  NSLog(@"Birthday selected is %@", birthday);

You can see that the value set in the picker is being read via the outlet connected to it.