出现 sheet 时,EnvironmentObject 不起作用
EnvironmentObject does not work when sheet is presented
我有一个具有 managedObjectContext(环境变量)的视图。在带有 NavigationLink 的 NavigationView 中呈现时,它工作正常。但当视图显示为 sheet 时,它不起作用。
当我保存一些实体数据时它给我一个错误。
"The operation couldn’t be completed. (Foundation._GenericObjCError error 0.)"
我在使用环境对象时是否遗漏了什么。我的代码
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
@Environment(\.managedObjectContext) var managedObjectContext
A sheet 不是 ContentView
的子组件。
因此,您必须将此环境单独传递给 sheet:
.sheet(isPresented: self.$isPresented, content: MySheetView().environment(\.self.moc)
其中 moc
在启动 sheet 的视图中定义为:
@Environment(\.managedObjectContext) var moc
我有一个具有 managedObjectContext(环境变量)的视图。在带有 NavigationLink 的 NavigationView 中呈现时,它工作正常。但当视图显示为 sheet 时,它不起作用。 当我保存一些实体数据时它给我一个错误。
"The operation couldn’t be completed. (Foundation._GenericObjCError error 0.)"
我在使用环境对象时是否遗漏了什么。我的代码
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
@Environment(\.managedObjectContext) var managedObjectContext
A sheet 不是 ContentView
的子组件。
因此,您必须将此环境单独传递给 sheet:
.sheet(isPresented: self.$isPresented, content: MySheetView().environment(\.self.moc)
其中 moc
在启动 sheet 的视图中定义为:
@Environment(\.managedObjectContext) var moc