Member-only story
Defining Custom Environment Keys in SwiftUI
When implementing apps using SwiftUI, we often need to access a view’s environment and read values from it. It’s easy to give environment a picture; think of it as a memory pool containing global values, shared and accessible all the way down to the view hierarchy.
SwiftUI framework sets several values to the environment by default. We can get them by declaring properties marked with the @Environment
property wrapper, passing as argument the key path that points to the value we are interested in.
To better demonstrate that, suppose that we have a Text view with the foreground color depending on the device’s current color scheme; different text color for light and dark mode. The key action here is to get the information about the device’s color scheme. Βut how do we do so in SwiftUI?
Color scheme is one of many system related values existing in the views’ environment by default. Τhe following declaration will make it available to any view:
With the colorScheme
being available, it's now easy to specify a different text color for each…