【问题标题】:SwiftUI Core DataSwiftUI 核心数据
【发布时间】:2020-09-24 15:55:19
【问题描述】:

当我使用 SwiftUI 界面和 SwiftUI 生命周期(勾选 Core Data)创建新项目时

一设置好,我就在模拟器上运行并得到一个白屏。

在预览中有一个填充列表 - 但没有编辑按钮

我正在使用 Xcode 12 (12A7209)。

如何使用模拟器,如何让工具栏正常工作?

【问题讨论】:

  • 白屏是因为Core Data中没有存储项目。预览中的列表在那里,因为 ContentView_Previews 使用了一个预览持久性控制器,它伪造了一堆项目,所以会有一些东西要显示。 (你剩下的问题,我不知道。)

标签: swift swiftui


【解决方案1】:

这似乎是一个小故障,但这里有一个解决方法。注意:我不知道这是否适用于非 iOS 设备。

将正文的内容包装在NavigationView 中删除工具栏并添加代码,如下所示:

import SwiftUI
import CoreData

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext
    
    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
        animation: .default)
    private var items: FetchedResults<Item>
    
    var body: some View {
        NavigationView {
            List {
                ForEach(items) { item in
                    Text("Item at \(item.timestamp!, formatter: itemFormatter)")
                }
                .onDelete(perform: deleteItems)
            }
            .navigationBarItems(leading: EditButton(),
                                trailing: Button(action: addItem) { Image(systemName: "plus") }
            )
        }
    }
    
    private func addItem() { /// From this line down, Apple's code works.

另外请注意,目前——我刚刚遇到了这个问题,这个解决方案适用于 Xcode 版本 12.3 (12C33)——你可能需要主动保存你的项目 (Command+S),退出 Xcode 并重新启动,以便 CoreData 的自动- 生成的实体“Item”可以在范围内找到。

【讨论】:

    【解决方案2】:

    这是按预期工作的。在模拟器中,核心数据堆栈中没有数据。所以列表没有什么可显示的,屏幕是空的。不幸的是,工具栏没有显示。

    对于预览,您正在使用已添加项目的堆栈。查看 Persistent 文件。您将找到一个添加项目的预览堆栈。对于使用环境中的 viewcontext 或 @FetchRequest 读取的所有视图,您需要将 viewcontext 添加到预览中。

     static var preview: PersistenceController = {
        let result = PersistenceController(inMemory: true)
        let viewContext = result.container.viewContext
    
        //-> adding items to show in the preview here
        for i in 0..<10 {
            let newItem = Task(context: viewContext)
            newItem.date = Date()
            newItem.content = "task with number \(i)"
        }
        
        do {
            try viewContext.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
        return result
    }()
    

    如果你想看更多,你可以检查一下

    【讨论】:

      猜你喜欢
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-06
      • 2020-12-03
      相关资源
      最近更新 更多