SwiftUI Preview issue with @State and CoreData

牧云@^-^@ 提交于 2021-02-11 13:42:11

问题


I'm having trouble getting a preview to work with what seems like a pretty simple struct. Customer is a CoreData entity:

struct CustomerDetailView: View {
    
    @Environment(\.managedObjectContext) var moc
    @State var showNewCustomer = false
    
    var customer: Customer
    
    var body: some View {

I've tried almost everything that doesn't work, including this:

struct CustomerDetail_Previews: PreviewProvider {
    static var previews: some View {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        return
            CustomerDetailView(customer: --Not sure what works here-- ).environment(\.managedObjectContext, context)
    
    }
}

I've tried static let customer = Customer() so that I would have a customer variable to use in the last line, but that did not help.


回答1:


Preview uses different container for apps, so you can just create new Customer, like

struct CustomerDetail_Previews: PreviewProvider {
    static var previews: some View {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        return
            CustomerDetailView(customer: Customer(context: context))
               .environment(\.managedObjectContext, context)
    
    }
}


来源:https://stackoverflow.com/questions/62898807/swiftui-preview-issue-with-state-and-coredata

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