gpt4 book ai didi

core-data - SwiftUI预览 Canvas 和核心数据

转载 作者:行者123 更新时间:2023-12-04 16:50:30 31 4
gpt4 key购买 nike

预览 Canvas 崩溃了,但是在模拟器中一切正常。我假设它与@ObservedObject和@Fetchrequest有关...

在这里尝试过的解决方案Previewing ContentView with CoreData

不起作用

 import SwiftUI
import CoreData

struct TemplateEditor: View {

@Environment(\.managedObjectContext) var managedObjectContext

@FetchRequest(
entity: GlobalPlaceholders.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \GlobalPlaceholders.category, ascending: false),
]
) var placeholders: FetchedResults<GlobalPlaceholders>


@ObservedObject var documentTemplate: Templates
@State private var documentTemplateDraft = DocumentTemplateDraft()
@Binding var editing: Bool


var body: some View {

VStack(){
HStack(){
cancelButton
Spacer()
saveButton
}.padding()
addButton
ForEach(placeholders) {placeholder in
Text(placeholder.name)
}
TextField("Title", text: $documentTemplateDraft.title)

TextField("Body", text: $documentTemplateDraft.body)
.padding()
.frame(width: 100, height:400)
Spacer()
}

...




}
struct TemplateEditor_Previews: PreviewProvider {
static var previews: some View {

let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Templates")
request.sortDescriptors = [NSSortDescriptor(keyPath: \Templates.created, ascending: false)]
let documentTemplate = try! managedObjectContext.fetch(request).first as! Templates


return TemplateEditor(documentTemplate: documentTemplate, editing: .constant(true)).environment(\.managedObjectContext, managedObjectContext).environmentObject(documentTemplate)

}
}


预期会产生预览

最佳答案

我不确定如果没有数据,您的try线是否会正常工作。

let documentTemplate = try! managedObjectContext.fetch(request).first as! Templates

为了让我的工作正常,我创建了一个要使用的测试项目。像这样:
struct DetailView_Previews: PreviewProvider {
static var previews: some View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
//Test data
let newEvent = Event.init(context: context)
newEvent.timestamp = Date()
return DetailView(event: newEvent).environment(\.managedObjectContext, context)
}
}

我还注意到,在托管CoreData View 的更早版本的tabView中,我需要.environment(.managedObjectContext,context)代码。否则预览将失败。

关于core-data - SwiftUI预览 Canvas 和核心数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57777915/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com