如何解决"environment object"这个问题?
How to solve this problem of "environment object"?
//环境对象class
class AppData: ObservableObject {
@Published var studs : [StudentModel]
}
var body: some View {
VStack{
List(appData.studs,id:\.rollNo){ s in //causing error
Text("\(s.rollNo)")
NavigationLink("", destination: StudentView(s: s))
}
}.navigationBarItems(trailing:
Button(action: {
self.addStud.toggle()
}){
Image(systemName: "plus")
.renderingMode(.original)
}
.sheet(isPresented: $addStud, content: {
AddStudent()
})
)
.navigationBarTitle(Text("Students"),displayMode: .inline)
}
Fatal error: No ObservableObject of type AppData found. A View.environmentObject(_:) for AppData may be missing as an ancestor of this view.
您的示例代码在视图的开头缺少一些行。根据错误消息的声音,您已经有了类似的东西:
struct MyView: View {
@EnvironmentObject var appData: AppData
// ...rest of view ...
}
除了用于从环境中为您的对象获取引用的代码外,您还需要确保在链的更上游某处将其放入。您的错误消息告诉你这就是问题所在 - 它正在环境中寻找一种 AppData
对象,但那里什么也没有。
假设您将其声明为应用级别;它可能看起来像这样:
@main
struct TestDemoApp: App {
// 1. Instantiate the object, using `@StateObejct` to make sure it's "owned" by the view
@StateObject var appData = AppData()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(appData) // 2. make it available to the hierarchy of views
}
}
}
您还需要做的是确保任何使用您的环境对象的视图也可以访问其 Xcode 预览中的一个。您可能想要创建一个包含示例数据的 AppData
版本,这样您的预览就不会与实时数据混淆。
extension AppData {
static var preview: AppData = ...
}
struct MyView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(AppData.preview)
}
}
//环境对象class
class AppData: ObservableObject {
@Published var studs : [StudentModel]
}
var body: some View {
VStack{
List(appData.studs,id:\.rollNo){ s in //causing error
Text("\(s.rollNo)")
NavigationLink("", destination: StudentView(s: s))
}
}.navigationBarItems(trailing:
Button(action: {
self.addStud.toggle()
}){
Image(systemName: "plus")
.renderingMode(.original)
}
.sheet(isPresented: $addStud, content: {
AddStudent()
})
)
.navigationBarTitle(Text("Students"),displayMode: .inline)
}
Fatal error: No ObservableObject of type AppData found. A View.environmentObject(_:) for AppData may be missing as an ancestor of this view.
您的示例代码在视图的开头缺少一些行。根据错误消息的声音,您已经有了类似的东西:
struct MyView: View {
@EnvironmentObject var appData: AppData
// ...rest of view ...
}
除了用于从环境中为您的对象获取引用的代码外,您还需要确保在链的更上游某处将其放入。您的错误消息告诉你这就是问题所在 - 它正在环境中寻找一种 AppData
对象,但那里什么也没有。
假设您将其声明为应用级别;它可能看起来像这样:
@main
struct TestDemoApp: App {
// 1. Instantiate the object, using `@StateObejct` to make sure it's "owned" by the view
@StateObject var appData = AppData()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(appData) // 2. make it available to the hierarchy of views
}
}
}
您还需要做的是确保任何使用您的环境对象的视图也可以访问其 Xcode 预览中的一个。您可能想要创建一个包含示例数据的 AppData
版本,这样您的预览就不会与实时数据混淆。
extension AppData {
static var preview: AppData = ...
}
struct MyView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(AppData.preview)
}
}