I have a simple detail view where users can input data. After pressing the save button, I would like the app to navigate back to the previous list view. The detail view is opened through a NavigationLink. I assume the action for the button needs to be adjusted in some way. Any advice is appreciated.
Navigate back after saving in Swift UI
hi,
since you tagged Core Data, i'll assume you are seeing a detail view of a Core Data object.
the situation depends on whether this is a live edit or not.
the loadStateVariables function would copy values from the core data object to the @State variables, and the commitDataEntry() function would copy values from the @State variables back to the object and then dismiss with the same presentationMode.wrappedValue.dismiss() call.
i'll leave it to the UI police about whether this is the best of policies.
hope that helps,
DMG
since you tagged Core Data, i'll assume you are seeing a detail view of a Core Data object.
the situation depends on whether this is a live edit or not.
if this is a live edit, any change you make in the Detail view to the fields of the object (which is already an ObservableObject, and you would indicate that it be an @ObservedObject in your code) is done immediately; using the Back button works as is.
if this is not a live edit, one might off-load all the values to be edited to @State variables when the view appears; those variables become the editable items; and when the user taps a Save button, the @State variables are copied back to the Core Data object to commit the edit.
Code Block // define this in your Detail view @Environment(\.presentationMode) var presentationMode // and you have some Core Data object for this View var myObject: MyCoreDataObject // and lots of View code, with the following modifiers attached .navigationBarBackButtonHidden(true) .navigationBarItems( leading: Button(action : { self.presentationMode.wrappedValue.dismiss() }){ Text("Cancel") }, trailing: Button(action : { self.commitDataEntry() }){ Text("Save") }) .onAppear(perform: loadStateVariables)
the loadStateVariables function would copy values from the core data object to the @State variables, and the commitDataEntry() function would copy values from the @State variables back to the object and then dismiss with the same presentationMode.wrappedValue.dismiss() call.
i'll leave it to the UI police about whether this is the best of policies.
hope that helps,
DMG
Thank you @DelawareMathGuy for a very helpful and concise answer! It solved my problem beautifully!