I am trying to create a SwiftData app using NavigationSplitView.
I started with a new SwiftData project for IOS. I updated ContentView like this:
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var items: [Item]
@State private var selection: Item?
var body: some View {
NavigationSplitView {
List(selection: $selection) {
ForEach(items) { item in
Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))
}
.onDelete(perform: deleteItems)
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
} detail: {
DetailView(selection: selection)
}
.navigationSplitViewStyle(.balanced)
}
private func addItem() {
withAnimation {
let newItem = Item(timestamp: Date())
modelContext.insert(newItem)
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
for index in offsets {
modelContext.delete(items[index])
}
}
}
}
#Preview {
ContentView()
.modelContainer(for: Item.self, inMemory: true)
}
and then I created DetailView.swift:
import SwiftUI
import SwiftData
struct DetailView: View {
var selection: Item?
var body: some View {
if let item = selection {
Text("Item at \(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))")
} else {
Text("nothing selected")
}
}
}
#Preview {
return DetailView(selection: Item(timestamp: Date()))
.modelContainer(for: Item.self, inMemory: true)
}
Item.swift is unchanged for how it was generated in the new project:
import Foundation
import SwiftData
@Model
final class Item {
var timestamp: Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
But when I add the declaration of an Item
in the #preview
of DetailView, the project no longer builds:
/var/folders/9j/8r6qn35j5jjf0gm3crp6gynw0000gn/T/swift-generated-sources/@__swiftmacro_12navSplitView4Item5ModelfMc_.swift:1:1 Type 'Item' does not conform to protocol 'PersistentModel'
What do I need to do to pass these @Model
objects around as parameter?