我试图了解为什么 SwiftUI Preview 不允许我这样做:
struct ItemCreateView: View {
@Environment(\.dismiss) var dismiss
@Environment(\.modelContext) private var modelContext
@Query private var collections: [Collection]
let selectedCollection: Collection
@State private var item = Item()
@State private var selectedImage: PhotosPickerItem? = nil
var body: some View {...}
}
#Preview {
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try! ModelContainer(for: Collection.self, configurations: config)
for number in 1...10 {
let col = Collection(name: "Test Collection \(number)")
container.mainContext.insert(col)
}
let selectedCollection = container.mainContext.fetch(Collection.self).first!
ItemCreateView(selectedCollection: selectedCollection).modelContainer(container)
}
错误是:
No exact matches in call to macro 'Preview'
Closure containing control flow statement cannot be used with
result builder 'PreviewMacroBodyBuilder'
但是,如果我将“Return”添加到最后一项。它会抱怨:Cannot use explicit 'return' statement in the body of result builder 'ViewBuilder'
但如果我不尝试从容器中获取随机元素,一切都会正常。
#Preview {
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try! ModelContainer(for: Collection.self, configurations: config)
for number in 1...10 {
let col = Collection(name: "Test Collection \(number)")
container.mainContext.insert(col)
}
let selectedCollection = Collection(name: "Test Collection 1")
return ItemCreateView(selectedCollection: selectedCollection).modelContainer(container)
}
^ 这有效。
我不确定我是否理解这里所有内容的关联,而且我似乎无法在网上找到有关该错误的信息。
提前感谢您的帮助。
参考模型
@Model
final class Collection {
var name: String
@Relationship(inverse: \Item.collection) var items: [Item]
var timestamp: Date
init(name: String = "", items: [Item] = [], timestamp: Date = Date()) {
self.name = name
self.items = items
self.timestamp = timestamp
}
}
代码位于宏中,并且位于结果生成器中,这会使编译器产生非常糟糕的错误消息。让我们将所有内容移出
#Preview
宏,并将其放入常规@ViewBuilder
函数中。let selectedCollection
现在,在以下行出现错误fetch
不接受元类型。您应该传入一个FetchDescriptor<Collection>()
。现在我们得到
因此只需添加
try!
。最后,不再有错误了,您可以将所有内容放回原处
#Preview
。