我有一个视图在SwiftUI名为"MyListsView"它要求列表类型为FetchedResults">
struct MyListsView: View {
let lists: FetchedResults<MyList>
}
主要问题是我如何在Xcode预览中使用它。主要原因是在Xcode预览中,我不能使用@FetchRequest属性包装器。@FetchRequest属性包装器允许我创建FetchResults。
static var previews: some View {
MyListsView(lists: HOW TO PASS FetchResults<MyList> HERE )
.environment(.managedObjectContext, CoreDataProvider.shared.viewContext)
}
这是在WWDC 2020上为SwiftUI构建应用程序预览中介绍的,在18:00他介绍了"中间视图"的概念,例如
struct MyListsView_Previews: PreviewProvider {
struct MyListViewContainer: View {
@FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: Item.timestamp, ascending: true)], animation: .default)
private var items: FetchedResults<Item>
var body: some View {
MyListsView(lists: items)
}
}
static var previews: some View {
MyListViewContainer()
.environment(.managedObjectContext, PersistenceController.preview.container.viewContext)
}
}
注意:在预览时一定要使用PersistenceController
的预览单例。