In this chapter, you will update WorldTrotter to create the view for MapViewController programmatically (Figure 6.1). In doing so, you will learn more about view controllers and how to set up constraints and controls (such as UIButtons) programmatically.
Currently, the view for MapViewController is defined in the storyboard. The first step, then, is to remove this view from the storyboard so you can instead create it programmatically.
In Main.storyboard, select the map view associated with Map View Controller and press Delete (Figure 6.2).
You learned in Chapter 5 that you create a view controller’s view programmatically by overriding the UIViewController method loadView().
Open MapViewController.swift and override loadView() to create an instance of MKMapView and set it as the view of the view controller. You will need a reference to the map view later on, so create a property for it as well.
import UIKit import MapKit class MapViewController: UIViewController { var mapView: MKMapView! override func loadView() { // Create a map view mapView = MKMapView() // Set it as *the* view of this view controller view = mapView } override func viewDidLoad() { super.viewDidLoad() print("MapViewController loaded its view.") } }
When a view controller is created, its view property is nil. If a view controller is asked for its view and its view is nil, then the loadView() method is called.
Build and run the application. Although the application looks the same, the map view is being created programmatically instead of through Interface Builder.