SwiftUI with Core Data getting Blank Screen in simulator in Xcode 12

旧街凉风 提交于 2021-01-04 07:36:47

问题


In XCode 12, if I create a new SwiftUI App and check the "Use Core Data" button, the resulting application (with no changes) shows a blank screen in simulator (as well as on a device). In preview it shows the example timestamps as expected. Why are the simulator/device not showing the example timestamps?


回答1:


If you want to see the sample inputs from the template (10 rows with timestamp) in your simulator, you need to change in App.swift:

let persistenceController = PersistenceController.shared

to

let persistenceController = PersistenceController.preview

Without this change, the template provided by Apple shows the sample input only in the canvas preview of ContentView. The Persistence.swift file has two static variables: shared and preview. The .shared one is just initiating an (empty) PersistenceController while the .preview static variable initiates a PersistenceController, adds ten items with the current time stamp to the viewContext and saves it.




回答2:


Clearing the data in the simulator did not work for me.

I'm struggling with .toolbar but find it only works with a NavigationView in the released XCode 12.

So if you're using the template that comes when you click to use Core Data, just add to the ContentView.




回答3:


clearing the data in simulator under "Device->Erase all content and settings" worked for me




回答4:


The toolbar items default code is broken in SwiftUI: Use this in the template code. Embed the List into a NavigationView and then The buttons in a HStack.

var body: some View {
    NavigationView { //added
    List {
        ForEach(items) { item in
            Text("Item at \(item.timestamp!, formatter: itemFormatter)")
        }
        .onDelete(perform: deleteItems)
    } .toolbar {
        
                    #if os(iOS)
                    HStack {  //added
                        EditButton()
                        Button(action: addItem) {
                            Label("Add Item", systemImage: "plus")
                        }
                    }//added
                    #endif

    }
    }//added NavView embed
}

Also to get the preview to work you need to change the PersistenceController to shared not preview.

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environment(\.managedObjectContext, PersistenceController.shared.container.viewContext)
    }
}


来源:https://stackoverflow.com/questions/64004888/swiftui-with-core-data-getting-blank-screen-in-simulator-in-xcode-12

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!