Force Dark Mode to the View in SwiftUI

In this article we are going to learn how to apply a specific colour scheme to a View regardless of the system dark mode.

Availability: iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0

Since its arrival in 2019 with iOS 13, dark mode has become a user favorite. App developers everywhere, crafting beautiful and functional interfaces . While users typically have the freedom to toggle between light and dark modes.

But there are some situation where a particular screen needs to use only the light or dark color scheme.

# Usage

To achieve this result in SwiftUI is simple. All we need to do is to use the environment() modifier on the view we need to use a specific color scheme.

Text("Thin Material") 
.padding()
.foregroundStyle(.primary)
.background(.thinMaterial)
.environment(\.colorScheme, .dark)

Here we forced the dark mode on a material, to learn more about materials you can read this article.

# Availability

This Modifier is Available for any View object.

To Apply a specific ColorScheme to an entire app, it can be applied to the rootView.

var body: some Scene { 
WindowGroup.{
NavigationView {
}.environment(\.colorScheme, .dark)
}
}

It does not work if applied to the WindowGroup.

 

Thank you for reading this article.