5
View Controllers

A view controller is an instance of a subclass of UIViewController. A view controller manages a view hierarchy. It is responsible for creating view objects that make up the hierarchy and for handling events associated with the view objects in its hierarchy.

So far, WorldTrotter has a single view controller, ConversionViewController. In this chapter, you will update it to use multiple view controllers. The user will be able to switch between two view hierarchies – one for viewing the ConversionViewController and another for displaying a map (Figure 5.1).

Figure 5.1  The two faces of WorldTrotter

Collage of two screenshots of the canvas depicting the use of multiple view controllers.

The View of a View Controller

As subclasses of UIViewController, all view controllers inherit an important property:

var view: UIView!

This property points to a UIView instance that is the root of the view controller’s view hierarchy. When the view of a view controller is added as a subview of the window, the view controller’s entire view hierarchy is added, as shown in Figure 5.2.

Figure 5.2  Object diagram for WorldTrotter

Object diagram illustrating the View Hierarchy of the WorldTrotter app.

A view controller’s view is not created until it needs to appear on the screen. This optimization is called lazy loading, and it can conserve memory and improve performance.

There are two ways that a view controller can create its view hierarchy:

  • in Interface Builder, by using an interface file such as a storyboard

  • programmatically, by overriding the UIViewController method loadView()

You saw the first approach in Chapter 3. First, you created a sample view hierarchy programmatically, then you switched to Interface Builder to create the interface for ConversionViewController using a storyboard file. You will continue to use Interface Builder in this chapter as you further explore view controllers. In Chapter 6, you will get experience creating programmatic views using loadView().

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset