Using View Controllers in iOS 13
View controllers are instances of a subclass of UIViewController. A view controller manages a view hierarchy. It is responsible for creating the 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 that displays some labels. In this chapter, you will update the app to use multiple view controllers. The user will be able to switch between two view hierarchies – one for the existing temperature conversion screen and another for a map (Figure 4.1).
FIGURE 4.1 The two faces of WorldTrotter
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 4.2.
FIGURE 4.2 Object diagram for WorldTrotter
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 to create a view controller’s view:
in Interface Builder, by using an interface file such as a storyboard
programmatically, by overriding the UIViewController method loadView()
While the view controller’s view will be created using one of those two approaches, that view’s hierarchy may be created entirely in Interface Builder, entirely in code, or a mixture of both.
WorldTrotter’s view hierarchy is currently created in Interface Builder using a storyboard. You will continue to use Interface Builder in this chapter as you further explore view controllers. In Chapter 5, you will get experience creating programmatic views using loadView().