I'm working on a SwitUI app that shows a list of items that I want to create/edit/delete. I've been working with Core Data, so I have a @FetchRequest in the view that retrieves the objects. Then a '+' button which creates a new object using the Core Data context, with a placeholder title, and adds it to the list. The user can then tap to edit an object in the list to add information to it using the editor view.
My question is, is there a way to programmatically open the editor view when a new object is created, passing in that same object?
I'm probably missing something simple, but I'm struggling to achieve this. I can't create the editor view in the parent view hierarchy, and show it by toggling a @State variable, as I don't have the newly created object at the time the View is instantiated.
Here's a bit of pseudocode to help illustrate more clearly:
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Object.title, ascending: true)],
animation: .default) private var objects: FetchedResults<Object>
@State var objectEditorIsActive: Bool = false
var body: some View {
List {
Button(action: {
addObject()
}, label: { Image(systemName: "plus") })
// List of existing objects, with a button to open ObjectEditor
// and pass in the corresponding object for editing.
NavigationLink(
destination: ObjectEditor(object: existingObject),
isActive: $objectEditorIsActive,
label: { ObjectView() })
}
}
func addObject() {
withAnimation {
let newObject = Object(context: viewContext)
newObject.title = "New Object"
try? viewContext.save()
// if this is successful, open ObjectEditor with newObject passed in.
// Via NavigationLink ideally, but in a sheet or any other method is fine.
}
}
So basically I want to open ObjectEditor and pass in newObject in one button press, rather than requiring the user to have to specifically select the newly created object every time.
Any help would be greatly appreciated!