Quick Tip – Detecting Color Scheme in SwiftUI

Quick Tip – Detecting Color Scheme in SwiftUI
⏱ Reading Time: < 1 min

It’s quite often necessary to know the current color scheme of a device in order to modify the displayed content of an app. For example, you may want to change the background color of a view, the foreground color of a text, to show different images or different text. The reasons can be many. And all that depending on the light or dark color mode.

In SwiftUI it’s super fast to detect and determine the current color scheme using the colorScheme environment key as follows:

The similarly named colorScheme property indicates the current color scheme, and can be used to apply a different set of configuration in views.

For example, the following creates a text where its background and foreground colors depend on whether the light or dark mode is currently active. Determining that mode is just a matter of a simple condition:

Text colors depending on both the light and dark mode

If you found this post useful then please consider sharing it! Also, subscribe to my newsletter in order to be notified about everything new published here directly in your inbox, and follow me on Twitter, on YouTube, on Medium and other social media.