About the 6. Programmatic Views category

#1

(Replace this first paragraph with a brief description of your new category. This guidance will appear in the category selection area, so try to keep it below 200 characters. Until you edit this description or create topics, this category won’t appear on the categories page.)

Use the following paragraphs for a longer description, or to establish category guidelines or rules:

  • Why should people use this category? What is it for?

  • How exactly is this different than the other categories we already have?

  • What should topics in this category generally contain?

  • Do we need this category? Can we merge with another category, or subcategory?

#2

Problem with code on page 100 (Programmatic Controls)

override func loadView() {
    // Create a map view
    mapView = MKMapView()
    // Set it as *the* view of this view controller
    view = mapView
    let segmentedControl = UISegmentedControl(items: ["Standard", "Hybrid", "Satellite"])
    segmentedControl.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.5)
    segmentedControl.selectedSegmentIndex = 0
    segmentedControl.translatesAutoresizingMaskIntoConstraints = false
    let topConstraint = segmentedControl.topAnchor.constraintEqualToAnchor(view.topAnchor)
    let leadingConstraint = segmentedControl.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor)
    let trailingConstraint = segmentedControl.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor)
    topConstraint.active = true
    leadingConstraint.active = true
    trailingConstraint.active = true
    view.addSubview(segmentedControl)
}

It crashes in the iPhone 6s Plus emulator at this statement…

topConstraint.active = true

The diagnostic is

2016-06-15 15:01:47.447 WorldTrotter[10891:1066330] *** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with items <UISegmentedControl: 0x7fcc4dd1bd60; frame = (0 0; 212 29); opaque = NO; layer = <CALayer: 0x7fcc4dd1c6d0>> and <MKMapView: 0x7fcc4ad531a0; frame = (0 0; 0 0); clipsToBounds = YES; layer = <CALayer: 0x7fcc4ad53020>> because they have no common ancestor. Does the constraint reference items in different view hierarchies? That's illegal.'

#3

Fixed the problem. After researching issue on stackoverflow and reading the exception diagnostic more carefully, I activated the constraints after adding the segmented control as a subview to the view. To put it another way, I needed to write the code exactly as it appears in the book then it works.