6
Programmatic Views

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.

Figure 6.1  WorldTrotter with programmatic views

WorldTrotter with programmatic views

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).

Figure 6.2  Deleting the view

Screenshot has the “Map view” under the Map Scene inside the Document Outline selected, and the canvas shows the Map View Controller, with its view controller icon selected.

Creating a View Programmatically

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.

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

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