Mitch Kelly
Mitch Kelly

Reputation: 491

How to center an MKMapView horizontally and vertically in a view controller?

I am attempting to center an MKMapView horizontally and vertically within a view controller:

enter image description here

Whenever I try to use the Auto Layout constraints, the map disappears when I run the app. Is there a way to center it programmatically so that it is in the center of the view controller and doesn't disappear.

The icon in the center of the map is simply a button that I am using as a marker to show the user what portion of the map they will mark if they hit the next button.

Thank you in advance for any help.

Upvotes: 1

Views: 67

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

Add it programmatically like this , also be careful to insert it beneath the marker

    lazy var myMapView = MKMapView()
    myMapView.delegate = self
    self.view.addSubview(myMapView)
    myMapView.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint(item:myMapView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0).isActive = true
    NSLayoutConstraint(item:myMapView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0).isActive = true
    NSLayoutConstraint(item:myMapView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.width, multiplier: 0.7, constant: 0).isActive = true
    NSLayoutConstraint(item:myMapView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.height, multiplier: 0.5, constant: 0).isActive = true

Upvotes: 1

Related Questions