import SwiftUI
import CoreData
struct CategoryOverview: View {
var category: Category
var body: some View {
VStack(alignment: .leading) {
HStack {
Text(category.name ?? "")
.font(.title)
Spacer()
}
Text(String(category.records?.count ?? 0))
.font(.subheadline)
}
.padding()
.foregroundColor(Color.white)
.background(Color.blue)
.clipShape(RoundedRectangle(cornerRadius: 10))
}
}
struct CategoryOverview_Previews: PreviewProvider {
static var previews: some View {
let category = Category()
category.id = UUID()
category.timestamp = Date()
category.name = "Clean"
return CategoryOverview(category: category)
}
}
I defined Category
entity in Core Data model. Then I built a simple view to show the name of a category. I tried to pass a Category
instance to the preview struct, but preview crashed always. There is no detail logs for this crash. It just said "the preview process appears to have crashed".
This view works well in other views such as main ContentView
. So, the code is fine, but I suspect that my preview code is wrong.
I'm very new to Swift and Swift UI. Did I miss something?
Since Category
is a Core Data model you need a context
change
let category = Category()
To something like
let category = Category(context: PersistentController.preview.container.viewContext)
If you use the standard setup. If not just fill in the context variable whichever way you traditionally use it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.