Hello, I am attempting to create my first project with a 100% programmatic UI. This project contains an MKMapView to show restaurants near the current user. The issue that I'm having, however, is that the MKMapView isn't showing up, even with the constraints that I've applied. I tried constraining a MKMapView in Storyboard and it shows up just fine. Did I forget to include something that the storyboard does for you? Did a do the constraints properly? Hopefully someone can shed some light on this. Thanks in advance.
My code is:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController {
var mapView: MKMapView!
var viewLocationsButton: UIButton!
override func loadView() {
self.view = UIView()
view.backgroundColor = .systemBackground
viewLocationsButton = UIButton()
viewLocationsButton.translatesAutoresizingMaskIntoConstraints = false
viewLocationsButton.backgroundColor = UIColor(red: 0, green: 0, blue: 0.75, alpha: 1)
viewLocationsButton.tintColor = .white
viewLocationsButton.setImage(UIImage(systemName: "mappin.and.ellipse"), for: .normal)
viewLocationsButton.layer.borderWidth = 1
viewLocationsButton.layer.borderColor = UIColor(red: 0, green: 0, blue: 0.75, alpha: 1).cgColor
viewLocationsButton.layer.cornerRadius = 15
viewLocationsButton.setTitle("Show Locations", for: .normal)
mapView = MKMapView()
mapView.translatesAutoresizingMaskIntoConstraints = false
mapView.mapType = .standard
mapView.centerCoordinate = CLLocationCoordinate2D(latitude: 37.0902, longitude: 95.7129)
#if os(macOS)
mapView.showsZoomControls = true
#endif
mapView.showsCompass = true
mapView.showsScale = true
mapView.isZoomEnabled = true
view.addSubview(mapView)
view.addSubview(viewLocationsButton)
setupConstraints()
}
override func viewDidLoad() {
super.viewDidLoad()
}
func setupConstraints() {
NSLayoutConstraint.activate([
viewLocationsButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20),
viewLocationsButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20),
viewLocationsButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20),
viewLocationsButton.heightAnchor.constraint(equalToConstant: 50),
mapView.topAnchor.constraint(equalTo: view.topAnchor),
mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
mapView.trailingAnchor.constraint(equalTo: view.leadingAnchor),
mapView.bottomAnchor.constraint(equalTo: viewLocationsButton.topAnchor, constant: -20)
])
}
}