Creating a View Programmatically

You learned in Chapter 4 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.

Listing 5.1  Creating a map view programmatically (MapViewController.swift)

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 and click the Map tab bar item to switch views. 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
3.15.156.140