I want to have simple app that has a sorted list of items. Clicking on each item goes into a detail view, where clicking another button updates a field of an item, which should redraw the original list.
The list view is given by:
import SwiftUI
import CoreData
struct ContentView: View {
@Environment(\.managedObjectContext) var context
@State private var itemName: String = ""
// get all data, sorted by date
@FetchRequest(
entity: Item.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Item.lastEdited, ascending: true)]
) var allItems: FetchedResults<Item>
var body: some View {
NavigationView {
List {
ForEach (allItems) { recipe in
NavigationLink(destination: DetailView(item: item).environment(\.managedObjectContext, self.context)) {
Text(item.name ?? "No name given")
} // nav link
}
}
}
}
and the detail view is given by:
import SwiftUI
import CoreData
struct DetailView: View {
@Environment(\.managedObjectContext) var context
var item: FetchedResults<Item>.Element
var body: some View {
Button (action: {
self.updateDate(item: self.item)
}) {
Text("Press me!")
}
} // body
func updateDate(item: Item) {
item.lastEdited = Date()
} // func
} // DetailView
Pressing the “Press Me” button on the detail view causes the update to work, and the list view to update, but this happens when I press the button:
- A new screen with the detail view is shown
- It goes back to the list view
Why does (1) happen? How do I avoid this?
I have Item defined as an Entity in my xcdatamodeld