When the NavigationLink is pressed I want to create an object (with the time when it was pressed), add it to the savedObjects
and pass then new object to the destination view.
How can I do this without changing the state while the view is updating?
struct ContentView: View {
@State private var savedObjects = [
MyObject(
id: 0,
date: Date()
),
MyObject(
id: 1,
date: Date()
),
MyObject(
id: 2,
date: Date()
),
MyObject(
id: 3,
date: Date()
)
]
var body: some View {
NavigationView {
List {
NavigationLink("Save new object and navigate to it", destination: DestinationView(object: MyObject(id: Int.random(in: 10...1000), date: Date())))
ForEach(savedObjects) { object in
NavigationLink("Navigate to object \(object.id)", destination: DestinationView(object: object))
}
}
}
}
}
class MyObject: ObservableObject, Identifiable {
var id: Int
var date: Date
init(id: Int, date: Date) {
self.id = id
self.date = date
}
}
struct DestinationView: View {
@ObservedObject var object: MyObject
var body: some View {
VStack {
Text("object \(object.id)")
Text("date: \(object.date.description)")
}
}
}