In SwiftUI how to ask user to save edits when dismissing a NavigationLink

I have a master detail arrangement of 2 views, a list on one from which the user selects a record in Core Data which links to a detail view (NavigationLink) where the user edits the corresponding record. On the edit view there is a Save button, but the big default dismiss button provided to the NavigationLink lets the user dismiss the view without saving, which is likely to happen.

Is there some modifier / event handler that will let me throw up an alert if the user has unsaved edits?

Replies

Without any code I can't know for sure if this will work but I just tried this in my MacOS app, which has a detail view appear in a sheet modal, and it works. In my detail view I also have a button that calls a save function. To dismiss my detail view I have the following button:

Button(action: {
		dismiss()
    }, label: {
		    Text("Back")
})

All I needed to do is add a call to my save function above "dismiss()"

Button(action: {
    FileManager().saveText(infoText!)
		dismiss()
    }, label: {
		    Text("Back")
})

Now when I hit the button to dismiss my detail view my save function runs, which shows a save dialog, and when I hit the "Save" button in the dialog it saves the file and then the detail view closes. I hope this helps!

  • But there you are adding a new Back button. I see that as a Cancel button. I wanted to insert an alert to say "Changes will be lost if you quit without saving Quit | Stay", or something like that.

    I am thinking I will avoid using the default NavigationLink behaviour and add my own buttons, as you are suggesting.

Add a Comment

You can use onDisappear in destinationView:

struct DestinationView: View {

    var body: some View {
        VStack {
          Text("Destination")
          // other stuff
          }
            .onDisappear {
                print("ContentView disappeared!")
            }
    }
}