Lesson 14

Pickers

A picker view is a user interface component that enables a user to pick a value from a set of related values using a slot machine–style interface. An example is shown in Figure 14.1.

Screenshot of picker view with a column of values: Mountain View, Sunnyvale, Cupertino (prominent in the center), Santa Clara, San Jose.

Figure 14.1

Each wheel of the picker view is called a component, and it is fairly common to have picker view with multiple components. Each component can have a different number of items in it (see Figure 14.2).

Screenshot of picker view with two columns, with the values: New York, London, Paris (prominent in the center), Chicago; and Hotels, Cinemas, Theaters (prominent in the center), Airports, Museums, Clubs.

Figure 14.2

A picker view is encapsulated by the UIPickerView class, which is part of the UIKit framework. Apple provides a special picker for allowing the user to select date and time. This component is called the date picker.

A picker requires a data source object and a delegate object. The data source object is one that implements the UIPickerViewDataSource protocol and provides information on the number of components, and rows-per-component, of the picker.

The delegate object implements the UIPickerViewDelegate protocol and has methods that are called when the current selection in a component has changed.

The delegate and data source objects could both be the same object, and in many cases the duties of these objects are performed by the view controller. However, it is very possible for them to be independent objects.

Creating a picker view is a simple matter ...

Get Swift iOS 24-Hour Trainer 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.