【问题标题】:How to solve this problem of "environment object"?如何解决“环境对象”这个问题?
【发布时间】:2021-07-22 13:34:03
【问题描述】:

//环境对象类

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)
    }

致命错误:未找到 AppData 类型的 ObservableObject。 AppData 的 View.environmentObject(_:) 作为该视图的祖先可能会丢失。

【问题讨论】:

    标签: swiftui environmentobject


    【解决方案1】:

    您的示例代码在视图开头缺少一些行。通过错误消息的声音,您已经有了类似的内容:

    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)
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-23
      • 1970-01-01
      • 2014-10-07
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 2021-11-28
      相关资源
      最近更新 更多