The app was pretty much complete and I was excited to show it off – but their phone was in Dark Mode and my app looked horrible! This is how to enable Dark Mode in SwiftUI. 🙂

Firstly, you need to be able to see what dark mode looks like on your app, so in the preview, I like to toggle between light and dark modes by commenting out the one mode I don’t want. But first, we need to detect the color scheme. Place it before the var Body: some View {…

@Environment(\.colorScheme) var colorScheme

Then, in the preview provider I have:

  .environment(\.colorScheme, .light)
//.environment(\.colorScheme, .dark)

As you can see the colorScheme is currently set to light. The app already looks OK in Light Mode, so to see what does not work, switch on Dark Mode.

//.environment(\.colorScheme, .light)
  .environment(\.colorScheme, .dark)

Now, either you can do some if/then magic to colours/images, eg:

Image(colorScheme == .dark ? "darkModeVersion\(hero.image)" : hero.image)

This means, if colorScheme is in Dark Mode then show darkModeVersion\(hero.image), or else show hero.image, or for different colours depending on the Colour Scheme, below.

.background(colorScheme == .dark ? : Color.white)

This does mean that there need to be assets for both, which can be a pain.

OR, you can create an image/colour asset in Assets.xcassets, eg: adaptiveBackgroundColor, below, are the 2 colours I would like used in each situation for backgrounds.

In this case, you only need to reference the colour to get both situations:


And tada!

Leave a Reply

Your email address will not be published. Required fields are marked *