ios - SwiftUI 模态环境

标签 ios swift swiftui

我不太明白使用模态时环境是如何工作的。看起来环境是与模态视图分开的。

我使用核心数据制作了一个快速示例,并将对象保存到核心数据。如果我不通过环境,则不会保存对象,并且在尝试保存对象时出现以下错误: 操作无法完成。 (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/

相关文章:

swift - 如何从 NSDictionary writeToURL 获取详细的错误消息?

swift - 在 ScrollView 中动态隐藏状态栏时滞后/屏幕卡住 (Swift 3)

animation - 简单的过渡动画在 SwiftUI 中不起作用

ios - View 更新期间我正在修改什么状态?

swiftui - 带有 SegmentedPickerStyle() 的选取器不会在 SwiftUI 中显示选取器标题

ios - Cordova IOS = >' Failed to load resource: An SSL error has occurred'

WWDC 2012 的 ios iPaint

swift - 学习 Swift,创建对象时不展开可选类型的值

ios - 如何使用 Storyboard缩小 iOS 应用程序中的 map ?

ios - 如果检测到超出范围,则禁用平移手势