[英]SwiftUI @EnvironmentObject shared in nested view
I'm having trouble trying to understand the hierarchy using SwiftUI's @EnvironmentObject wrapper.我在尝试使用 SwiftUI 的 @EnvironmentObject 包装器来理解层次结构时遇到了麻烦。 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:我有一个需要在应用程序内的多个屏幕中访问的 ViewModel,所以我将此代码放在主应用程序文件中:
var chartsModel = ChartsViewModel()
Inside the ContentView file generated by Xcode on a new project I have put this inside the ContentView_Previews在新项目中由 Xcode 生成的 ContentView 文件中,我已将其放入 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 内部有一个需要来自 ViewModel 的数据的 2 个级别的视图。
ContentView()->HomeView()->ChartView()
ChartView is a child of HomeView() ChartView 是 HomeView() 的子视图
I can get ChartView to display the data when in preview mode by using the following code.通过使用以下代码,我可以让 ChartView 在预览模式下显示数据。
@EnvironmentObject var viewModel: ChartsViewModel
The problem is when previewing HomeView, ContentView or running the app on a device nothing is outputted.问题是在预览 HomeView、ContentView 或在设备上运行应用程序时没有输出任何内容。
Inside the ContentView file generated by Xcode on a new project I have put this inside the ContentView_Previews在新项目中由 Xcode 生成的 ContentView 文件中,我已将其放入 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 !!
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.