I'm trying to clean up my code a bit by creating another file/view called DetailView that will display all the actual values for each item when the user clicks on them from the 'ForEach' code. However, its giving me an error of: Missing argument for parameter 'item' in call and its throwing it on the DetailViews_Previews. Why and how do I fix this? Thanks.
LISTVIEW
struct ListView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath:\Item.todaysDate, ascending: false)],animation: .default)
private var items: FetchedResults<Item>
var body: some View {
NavigationView {
List {
ForEach(items) { item in
NavigationLink {
DetailView(item:item).environment(\.managedObjectContext, self.viewContext)
} label: {
VStack {
Text("\(item.hoursSlept, specifier: "%.2f") hrs")
.bold()
.font(.system(size:18))
.padding(.trailing, 50)
}
}
}}}}}
DETAILVIEW
struct DetailView: View {
@Environment(\.managedObjectContext) private var viewContext
@ObservedObject var item: Item
var body: some View {
VStack {
if item.headacheToggle == true {
Image(systemName: "checkmark.circle").imageScale(.large)
.foregroundStyle(.red)
.font(.system(size:15))
}
else {
Image(systemName: "x.circle").imageScale(.large)
.foregroundStyle(.green)
.font(.system(size:15))
}
}
}}
struct DetailView_Previews: PreviewProvider {
static var previews: some View {
DetailView().environment(\.managedObjectContext, ListViewModel.preview.container.viewContext)
}
}
CodePudding user response:
You need to fetch an item from the preview context, here is one way:
struct DetailView_Previews: PreviewProvider {
static var firstItem: Item? {
let context = PersistenceController.preview.container.viewContext
let fetchRequest = Item.fetchRequest()
fetchRequest.fetchLimit = 1
let results = try? context.fetch(fetchRequest)
return results?.first
}
static var previews: some View {
if let item = firstItem {
DetailView(item: item)
}
else {
Text("Item not found")
}
}
}