Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterfriese/4be999cc942cbed5f5e844c70cf9476f to your computer and use it in GitHub Desktop.
Save peterfriese/4be999cc942cbed5f5e844c70cf9476f to your computer and use it in GitHub Desktop.
import SwiftUI
class AppState: ObservableObject {
@Published var counter = 0
}
struct ContentView: View {
@EnvironmentObject var state: AppState
@State var presentDetailsView = false
@State var presentDetailsViewNoEnvironment = false
var body: some View {
NavigationView {
VStack {
Button(action: { self.state.counter += 1 }) {
Text("Current value: \(state.counter)")
}
// 1: this works fine
NavigationLink(destination: DetailsView()) {
Text("Navigate to details")
}
Button(action: { self.presentDetailsView = true }) {
Text("Present details")
}
Button(action: { self.presentDetailsViewNoEnvironment = true }) {
Text("Present details w/o Environment (will crash)")
}
}
.navigationBarTitle("@EnvironmentObject: Master")
// 2: this crashes
.sheet(isPresented: $presentDetailsViewNoEnvironment) {
DetailsView()
}
// 3: (instead of 2): this works fine
.sheet(isPresented: $presentDetailsView) {
DetailsView().environmentObject(self.state)
}
}
}
}
struct DetailsView: View {
@EnvironmentObject var state: AppState
var body: some View {
Text("The value is \(state.counter)")
}
}
@peterfriese
Copy link
Author

Looking at the view hierarchy in the view debugger, we can see that thethis actually makes sense, as a modal screen is added to the view hierarchy in parallel to the original ContentView.

When navigating from ContentView to DetailsView using a NavigationLink, DetailsView becomes a child of ContentView:

navigate

When displaying a modal sheet using sheet(isPresented:content:), however, DetailsView will not become a child of ContentView. Instead, the hosting view will be instantiated in parallel to the originating view:

modal

The entire project can be found here: https://github.com/peterfriese/Swift-EnvironmentObject-Demo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment