How can I turn the MKMapView for dark mode?

Viewed 5452

How can I change the map to dark mode from iOS 13?

I have opt-out from UserInterfaceStyle so system-wide colors will not apply to me, so I'll do it manually.

I've seen this video from apple WWDC2019 - Session 236, at 8:19s but that's for snapshots and I didn't get it.

Actually I was trying something like:

private var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()
    mapView.backgroundColor = .black       
}

but it doesn't change the theme or appearance or the traitCollection to dark.

Any suggestion?

3 Answers

This is what you need on the viewDidLoad

if #available(iOS 13.0, *) {
    self.overrideUserInterfaceStyle = .dark
}

Setting overrideUserInterfaceStyle on viewDidLoad method will force that view controller to use the desired mode you specify.

 if #available(iOS 13.0, *) {
     overrideUserInterfaceStyle = .light
 }

MapSnapShot

if you are trying to take a snapshot and confused with output image colour Use

 if #available(iOS 13.0, *) {
     mapSnapshotOptions.traitCollection = traitCollection
 }

Full code for a MKMapSnapshotter

func mapCamera(location : CLLocationCoordinate2D )-> MKMapSnapshotter {
    let mapSnapshotOptions = MKMapSnapshotter.Options()
       
    let region = MKCoordinateRegion(center: location, latitudinalMeters: 500, longitudinalMeters: 500)
    mapSnapshotOptions.region = region
    mapSnapshotOptions.scale = UIScreen.main.scale
    mapSnapshotOptions.size = AppConstants.Size.mapDetailView
    mapSnapshotOptions.showsBuildings = true
    mapSnapshotOptions.showsPointsOfInterest = true
    if #available(iOS 13.0, *) {
        mapSnapshotOptions.traitCollection = traitCollection
    }
    return MKMapSnapshotter(options: mapSnapshotOptions)
}

In case you got here searching for a macOS solution (like me), simply update the appearance property on MKMapView:

if #available(OSX 10.14, *) {
    mapView.appearance = NSAppearance(named: .darkAqua) // .aqua for default mode
}
Related