DEV Community

Thomas Prezioso Jr.
Thomas Prezioso Jr.

Posted on

3 1

How to Detect Dark Mode in SwiftUI

SwiftUI makes it really simply to detect when dark mode is enabled. We simply have to add a @Enviroment variable and use .colorScheme property to scan the settings on our device and see if dark mode is enabled.

Let's take a look at the example below.

struct ContentView: View {
    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        ZStack {
            Color(colorScheme == .light ? .blue : .red)
            Text("Hello, World!")
        }
    }
}

In the code above we are creating the @Environment variable to see if our device is in dark mode. Then inside of our body view we are setting the background color to red if its in dark mode or blue if its not in dark mode by using our colorScheme variable inside of a ternary operator.

A great use case for this is if you want to support different custom UI's for when the users device is in dark mode.

🌃 Happy Coding! 🌃

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay