MKMapView and constraints


How come the MKMapView can be created and set as the MapViewController’s view without the need to specify layout constraints?


This is because the map view is the view for the MapViewController. As such, it is always stretched to fill the entire space that the view controller takes up. Think back to the Quiz project from Chapter 1; it has a white, plain UIView as the ViewController’s view (filling the same role as the map view for the MapViewController), yet you never had to set up constraints for it. The white view was stretched to fill the entire space.

1 Like

Thanks Christian, I kinda want to expand on this though. In the map scenario it’s great because we are ok with the map being behind the status bar. When it comes to the bronze challenge though, I don’t want the web page cut off by the status bar. I tried to set the constraints for the main view like so

let topConstraint = view.topAnchor.constraintEqualToAnchor(topLayoutGuide.bottomAnchor, constant: 16) = true

It seems like this doesn’t work in loadView. Is topLayoutGuide not instantiated yet or does it only account for the status bar in subviews?



it’s great because we are ok with the map being behind the status bar

We are?! I’m not okay with that.

I don’t want the web page cut off by the status bar

  1. A TabBarController uses a custom layout for its view, and the MapView and the WebView are automatically inserted into that custom layout.

  2. In the storyboard, I tried to constrain the top of the WebView, and the storyboard would not let me do that.

  3. I tried to constrain the top of the WebView programmatically, and at runtime iOS broke the constraint.

  4. There’s a UIViewController method named func preferredStatusBarStyle() -> UIStatusBarStyle, but the opaque style was deprecated then removed.

  5. As a result, it is clear to me that Apple does not want us to design UI’s that do not underlap the status bar.

  6. However, if you wish to thwart Apple’s desires, before creating a WebView, first create a generic UIView. The UIView will completely fill the window–and underlap the status bar. The layout of the UIView will be controlled by the TabBarController, i.e. it’s out of your control. Next, add a WebView to the UIView. You have complete control over the layout of a subview within the UIView, so you can add a gap between the top of the UIView and the top of the WebView. The gap will prevent the WebView from underlapping the status bar. To create the gap, you can add a constraint from the WebView to the topLayoutGuide (which will be the bottom edge of the status bar).