Home > OS >  How can I change Mapbox style URL when device switches light/dark mode?
How can I change Mapbox style URL when device switches light/dark mode?

Time:03-05

In my SwiftUI app I am using Mapbox and have two style URL's: One for light-mode and one for dark-mode.

Right now I am using the code below to switch style URL's in my constants file which only works if I perform a fresh build of the app...

let MAPBOX_STYLE_URL : String = {
    if UITraitCollection.current.userInterfaceStyle == .dark {
        return "mapbox://styles/customDarkModeUrl" 
    }
    else {
       return "mapbox://styles/customLightModeUrl" 
    }
}()

Where can I make the app adapt the style URL every time the device switches to dark-mode?

Could I put this code in SceneDeletegate's willEnterForeGround or didBecomeActive?? I am not sure how to perform this style url update?

Thank you!

CodePudding user response:

You just need to monitor your environment color scheme on your view:

struct ContentView: View {

    @Environment(\.colorScheme) var colorScheme

    var mapboxStyleURL: String {
        "mapbox://styles/custom"   (colorScheme == .dark ? "Dark" : "Light")   "ModeUrl" 
    }

    var body: some View {
        Text(mapboxStyleURL)
    }
}
  • Related