Created
August 14, 2019 19:47
-
-
Save peterfriese/4be999cc942cbed5f5e844c70cf9476f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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:
The entire project can be found here: https://github.com/peterfriese/Swift-EnvironmentObject-Demo