SwiftUI Preview doesn't work with FetchRequest and Init

↘锁芯ラ 提交于 2020-02-04 05:29:05

问题


I have a problem with SwiftUI Preview not working sometimes (but not giving me any errors, just a blank Canvas). I have narrowed down the problem - it doesn't work when I'm using fetchRequest with init. But I don't know what to do next.

Preview works with this code:

import SwiftUI

struct ListView: View {

    var fetchRequest = FetchRequest<NPBooking>(entity: NPBooking.entity(), sortDescriptors: [])
    var bookings: FetchedResults<NPBooking> { fetchRequest.wrappedValue }

    var body: some View {
        ForEach(bookings, id: \.self) { booking in
            Text("item")
        }
    }

}

struct ListView_Previews: PreviewProvider {
    static var previews: some View {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        //Test data
        let testBooking = NPBooking.init(context: context)
        testBooking.date = Date()
        testBooking.name = "name"
        return ListView().environment(\.managedObjectContext, context)
    }
}

Preview doesn't work with this code:

import SwiftUI

struct ListView: View {

    var fetchRequest: FetchRequest<NPBooking>
    var bookings: FetchedResults<NPBooking> { fetchRequest.wrappedValue }

    var body: some View {
        ForEach(bookings, id: \.self) { booking in
            Text("item")
        }
    }

    init(startDateOfMonth: Date) {
        fetchRequest = FetchRequest<NPBooking>(entity: NPBooking.entity(), sortDescriptors: [
            NSSortDescriptor(keyPath: \NPBooking.date, ascending: true)
        ], predicate: NSPredicate(format: "date >= %@", startDateOfMonth as NSDate))
    }

}

struct ListView_Previews: PreviewProvider {
    static var previews: some View {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        //Test data
        let testBooking = NPBooking.init(context: context)
        testBooking.date = Date()
        testBooking.name = "name"
        return ListView(startDateOfMonth: Date()).environment(\.managedObjectContext, context)
    }
}

I guess I need to add some test data for this init or fetchRequest or both? Tried few things and I cannot manage to make it work.


回答1:


The Code works fine if you change your call in previews to

 ListView(startDateOfMonth: Date().addingTimeInterval(-86400 * 30)).environment(\.managedObjectContext, context)

Your startDateOfMonth var gets set to 30 days before today with this lines



来源:https://stackoverflow.com/questions/59963714/swiftui-preview-doesnt-work-with-fetchrequest-and-init

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