Skip to content

Instantly share code, notes, and snippets.

@Simulacrotron
Last active May 12, 2023 20:37
EnvironmentObject Example
import SwiftUI
struct EnvironmentParentView: View {
@StateObject private var myObject = MyObject()
var body: some View {
VStack(spacing: 16) {
Text("The parent passed down myObject as an environment, so any view in it's hierarchy can reference it, but only if they need to")
.font(.title)
Text(myObject.someFlag ? "✅" : "❌")
EnvironmentChild()
}
// This is how any subviews that care about myObject can get a reference
.environmentObject(myObject)
}
}
struct EnvironmentChild: View {
var body: some View {
VStack {
Text("No need for myObject reference, even though the grandchild does")
EnvironmentGrandchild()
}
}
}
struct EnvironmentGrandchild: View {
// By referencing this enviroment object the grandchild just magically gets access to it
@EnvironmentObject private var myObject: MyObject
var body: some View {
VStack {
Button("Toggle") {
myObject.someFlag.toggle()
}
.buttonStyle(.borderedProminent)
}
.padding()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment