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

In 2019 with iOS 13, Apple introduced the so loved dark mode and since then we all use it and develop apps taking into account a second set of colours.

Usually it is the user who decides whether to enable the dark mode or not.

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 really 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 to any View object.

To apply a specific color scheme to the entire app, it can be applied to the root view.

var body: some Scene {

WindowGroup {

NavigationView {

}

.environment(\.colorScheme, .dark)

}

}

Warning

It does not work if applied to the WindowGroup.

If you have any question about this article, feel free to email me or tweet me @franceleonidev and share your opinion.

Thank you for reading and see you in the next article!

Source link