我不太明白使用模态时环境是如何工作的。看起来环境是与模态视图分开的。
我使用核心数据制作了一个快速示例,并将对象保存到核心数据。如果我不通过环境,则不会保存对象,并且在尝试保存对象时出现以下错误: 操作无法完成。 (Foundation._GenericObjCError 错误 0。)
如果我在模式环境中传递托管对象上下文,它就可以工作。我注释掉了使它起作用的行。
谁能解释一下为什么会发生这种情况吗?
@FetchRequest(fetchRequest: ToDoItem.fetchAllItems()) var items
@Environment(\.managedObjectContext) var managedObjectContext
@State var showAddModal = false
var body: some View {
VStack {
List(items, id: \.name) { item in
Text(item.name)
}
Button(action: {
self.showAddModal.toggle()
}) {
Text("Add item")
}.sheet(isPresented: $showAddModal) {
ModalView()
// .environment(\.managedObjectContext, self.managedObjectContext)
// It works if the managed object context is passed in the modal's environment
}
}
}
}
struct ModalView: View {
@State var toDoItemName: String = ""
@Environment(\.presentationMode) var presentationMode
@Environment(\.managedObjectContext) var managedObjectContext
var body: some View {
VStack {
TextField("Item name", text: $toDoItemName)
Button(action: {
let toDoItem = ToDoItem(context: self.managedObjectContext)
toDoItem.name = self.toDoItemName
do {
try self.managedObjectContext.save()
} catch {
print(error.localizedDescription)
}
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Add")
}
}
}
}```
最佳答案
它应该自动通过,但没有。
"if view A presents view B as a sheet then they don’t automatically share environment data, and we need to send it in by hand. Apple has described this sheet situation as a bug that they want to fix, so I’m hopeful this will change in a future update to SwiftUI." - Paul Hudson - Hacking With Swift
我不知道他的消息来源,但他平时似乎知道自己在说什么。
关于ios - SwiftUI 模态环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58240409/