GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

SwiftUI and SwiftData: how can I tell if a user hit the cancel button instead of saving?

Forums > Articles

I was going through https://www.hackingwithswift.com/articles/263/build-your-first-app-with-swiftui-and-swiftdata and have a question: it is creating a new Person object every time a user hits the + button. What do I do if the user hits + by accident and wants to back out? How can I let the main view know that the user came back by clicking a cancel button instead of a save button?

Max

   

When the user taps a "Cancel" button you can have a method that modelContext.delete(person)

PS you will need to disable the "Back" Button from the navigation bar and maybe a "Done" back to dismiss the View which can have a disable if the name.isEmpty

   

That makes sense, thanks! Is there also a way to implement a kind of callback to the view that triggered the EditPersonView to appear and to pass some data back? Just wondering if that might come in handy one day.

   

@max asks:

Is there also a way to implement a kind of callback to the view that triggered
the EditPersonView to appear and to pass some data back?

A common approach is to have the same object in the primary view and the detail view.

So when you change a person object in the detail, you don't need to "pass some data back." There is only one object and it is shared between the two views.

Keep Coding!

   

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until February 9th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.