2.4. Picking Values with UIPickerView

Problem

You want to allow the users of your app to select from a list of values.

Solution

Use the UIPickerView class.

Discussion

A picker view is a graphical element that allows you to display series of values to your users and allow them to pick one. The Timer section of the Clock app on the iPhone is a great example of this (Figure 2-11).

A picker view on top of the screen

Figure 2-11. A picker view on top of the screen

As you can see, this specific picker view has two separate and independent visual elements. One is on the left and one is on the right. The left component is displaying hours (such as 0 hours, 1, 2, etc.) and the component on the right is displaying minutes (such as 18, 19, 20 mins, 21, 22, etc.). These two items are called components. Each component has rows. Any item in any of the components is in fact represented by a row, as we will soon see. For instance, in the left component, “0 hours” is a row, “1” is a row, etc.

Let’s go ahead and create a picker view on our view controller’s view. If you don’t know where your view controller’s source code is, please have a look at Recipe 2.2, where this subject is discussed.

First let’s go to the .h (header) file of our view controller and define our picker view:

#import <UIKit/UIKit.h>

@interface Picking_Values_with_UIPickerViewViewController
           : UIViewController

@property (nonatomic, strong) UIPickerView *myPicker;

@end

Now let’s ...

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.