I'm not sure how to pull off a viewer/editor with SwiftData + SwiftUI that supports Cancel
I want the user to be able to:
- Tap + to bring up a sheet/form to create a new Item.
- The navigation bar shows Cancel and Create.
- Create is only enabled when the fields are mostly valid.
- Tap Create to do a deeper validation and add.
- Tap Cancel to not make any changes.
- Tap an item to view it.
- Tap Edit when viewing to edit.
- The navigation bar shows Cancel and Done.
- Done is only enabled when the fields are mostly valid.
- Tap Done to do a deeper validation and save changes.
- Tap Cancel to not make any changes.
I think is a fairly common pattern. It's used by Contacts, for instance.
I've got parts of this working. Creating is easy: I just insert
it only after the user taps Create and it's validated.
But Edit/Cancel/Done seems harder. If I disable autosaving the changes to the model, the changes are applied to other parts of SwiftUI immediately. And I haven't figured out how to cancel the changes. Should I be operating on a copy of the object instead? How do I copy it in a way that doesn't impact SwiftData?
I'm happy to take any tips you might have, but if you want to look at the code and suggest something that way I put my test case up here: https://github.com/tewha/ItemEditor My hope is I can get this sample working, get the changes into my app, and keep the sample up for others to discover (though I feel this would also be a great concept for sample code).