我有一个SwiftUI预览有时无法正常工作的问题(但没有给我任何错误,只是一个空白的Canvas)。 我已经缩小了问题的范围-当我将fetchRequest与init一起使用时,它不起作用。但是我不知道下一步该怎么做。
预览使用以下代码:
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)
}
}
我想我需要为此init或fetchRequest或这两者添加一些测试数据?尝试了几件事,但我无法使其正常工作。
答案 0 :(得分:2)
如果您将预览中的通话更改为
,则该代码可以正常工作 ListView(startDateOfMonth: Date().addingTimeInterval(-86400 * 30)).environment(\.managedObjectContext, context)
此行将您的startDateOfMonth变量设置为今天前30天