A linked View property that reads a `ObservableObject` supplied by an ancestor view that will automatically invalidate its view when the object changes.
State Management
Share Data between Views using @EnvironmentObject
classUser:ObservableObject {@Publishedvar name ="Enes Karaosman"}// View 1structEditView:View {@EnvironmentObjectvar user: Uservar body: some View {TextField("Name", text: $user.name) }}// View 2structDisplayView:View {@EnvironmentObjectvar user: Uservar body: some View {Text(user.name) }}// Container View to demonstrate communicationstructDemoView:View {let user =User()var body: some View {VStack {EditView()//.environmentObject(user)DisplayView()//.environmentObject(user) }// Since both views wrapped by same container// We can bind here as well. .environmentObject(user) }}
EnvironmentObject does not require to be passed explicitly down to child views.
// Lets demonstrate the information above// Dummy class for testing EnvironmentObjectclassEnvTest:ObservableObject {@Publishedvar testStr ="inital"}// In SceneDelegate, add thoselet envTest =EnvTest()let contentView =ContentView()// Assume ContentView is initial View .environmentObject(envTest)structContentView:View {// Now we are able to read environmentObject // passed from SceneDelegate, could be anywhere@EnvironmentObject()var envTest: EnvTestvar body: some View {VStack(spacing:16) {Text("Main")TextField("Placeholder", text: $envTest.testStr) .textFieldStyle(RoundedBorderTextFieldStyle())Rectangle().foregroundColor(.red).frame(height:2)Child1()// Dummy Child View }.padding() }}