本文介绍了SwiftUI预览不适用于FetchRequest和Init的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个SwiftUI预览有时无法正常工作的问题(但没有给我任何错误,只是一个空白的Canvas)。
我已经缩小了问题范围-当我将fetchRequest与init一起使用时,此问题不起作用。但是我不知道下一步该怎么做。

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.

预览版可使用以下代码:

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)
    }
}

预览不适用于以下代码:

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.

推荐答案

代码如果您将预览中的呼叫更改为

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

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

您的startDateOfMonth var设置为今天前30天,这行

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

这篇关于SwiftUI预览不适用于FetchRequest和Init的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 02:59