Detect Light and Dark Mode in SwiftUI


In this tutorial, you are going to learn how to detect if dark mode or light mode is enabled in the device with SwiftUI. Depending upon this you can control the flow of your program in app development, in most cases adjusting the color in the app.

In SwiftUI, you can use the ColorScheme environment key that can detect the light or dark mode. Even it can detect instant changes in the device settings. In other words, SwiftUI can update this value when changing the settings in the device.

The ColorScheme key enumerates the setting options for dark and light modes. You can use the value of this key to adjust the colors (background and foreground) in the app or make changes to the values of some variables.

A simple example of detecting light or dark mode of a device

Below is given a simple example of using the ColorScheme from Environment:


    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        
        Text(colorScheme == .dark ? "Currently Dark Mode" : "Currently Light Mode")
        
    }

In the above program, we have written the SwiftUI code that will show different text value depending upon the dark or light mode.

At the beginning, we have declare the environment variable colorScheme and then in the view, we are checking its value and showing up different text depending on dark or light mode.

Using if…else statement with colorScheme environment key

You can also use if...else statement to execute different code block depending on the value of colorScheme. Below is an example where we are showing up different message with SwiftUI Text view for dark and light mode:


    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        
        if(colorScheme == .dark) {
            Text("ITS DARK")
        } else if(colorScheme == .light) {
            Text("ITS LIGHT")
        }
        
    }
    

If we run the above program, it will show the message ITS DARK when dark mode is enabled. If we change the dark mode into light mode in the settings, SwiftUI automatically detect it and change the message to ITS LIGHT.