SwiftUI Data Flow @Environment (Values)
SwiftUI Data Flow @Environment (Values)
Read system- or app-provided values like color scheme and locale using @Environment.
Read environment values (color scheme)
Access the current color scheme from the environment and display it in the UI.
Example
import SwiftUI
struct EnvironmentDemo: View {
@Environment(\.colorScheme) var scheme
var body: some View {
Text(scheme == .dark ? "Scheme: Dark" : "Scheme: Light")
.padding()
}
}
import SwiftUI
struct ContentView: View {
var body: some View { EnvironmentDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
The example above shows a shared object from an ancestor using .environmentObject and consume it in descendants via @EnvironmentObject.