Force Dark Mode to 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.

Francesco Leoni

1 min read

Availability

iOS 13.0

macOS 10.15

tvOS 13.0

watchOS 6.0

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!

Share this article

Related articles


Combine CoreData and SwiftUI

See how to use CoreData database with SwiftUI. Syncing changes from CoreData to every View of your app.

5 min read

SwiftUICoreData

SwiftData the Successor of CoreData Explained with SwiftUI

Discover the SwiftData framework built on top of CoreData. Save and fetch data locally. Available for Xcode 15, Swift and SwiftUI.

5 min read

SwiftUICoreData

Make your Chart Scrollable with SwiftUI Charts (iOS 17)

Discover the new SwiftUI Charts APIs that enables you to create scrollable chart easily. Available for Xcode 15 and iOS 17.

2 min read

ChartsSwiftUI