简体   繁体   中英

SwiftUI @EnvironmentObject shared in nested view

I'm having trouble trying to understand the hierarchy using SwiftUI's @EnvironmentObject wrapper. I've got a ViewModel that needs to be accessed in multiple screens within the app so I've put this code inside the main app file:

var chartsModel = ChartsViewModel()

Inside the ContentView file generated by Xcode on a new project I have put this inside the ContentView_Previews

ContentView().environmentObject(ChartsViewModel())

Where I'm now getting confused is I have a view 2 levels deep inside ContentView that needs data from the ViewModel.

ContentView()->HomeView()->ChartView()

ChartView is a child of HomeView()

I can get ChartView to display the data when in preview mode by using the following code.

@EnvironmentObject var viewModel: ChartsViewModel

The problem is when previewing HomeView, ContentView or running the app on a device nothing is outputted.

Inside the ContentView file generated by Xcode on a new project I have put this inside the ContentView_Previews

You should do this not only in preview provider (which is for Preview mode), but in scene creation as well (so it works for runtime), like

@main
struct SwiftUI2App: App {
    var chartsModel = ChartsViewModel()

    var body: some Scene {
        WindowGroup {
            ContentView().environmentObject(ChartsViewModel())   // << here !!
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM