ovatsug25
ovatsug25

Reputation: 8616

How to allow a button that creates a new object in SwiftUI from not making an object on reload?

So I'm making a button for a "New Note" in Swift UI similar to the Apple Notes app.

Right now my "New Button" is a "Navigation Link" like so:

NavigationLink(
     destination: EditorView(makeNewNote())
) {
    Text("New")
}

Unfortunately—this triggers my app to create a new note every time the view loaded. :(

:/A note a second

I've been looking for a way to initate a segue on button push but I'm not finding success on this yet.

When I tried a modal—I found myself having the same problem

Button("New") {
    self.isNew = true
 }.sheet(isPresented: $isNew, content: {
    EditorView(makeNewNote())
 })

I'm wondering what the best way to approach this would be.

Having no success :(

Edit:

I referred to this and the documentation but I haven’t found a way to segue via a button push which would be ideal. (The function dosent get triggered in the closure :)

https://www.hackingwithswift.com/quick-start/swiftui/how-to-push-a-new-view-onto-a-

Also...if you were curious what makeNewButton() does—it basically inserts a new Core Data object into my app’s managed context.

Upvotes: 1

Views: 497

Answers (1)

thisIsTheFoxe
thisIsTheFoxe

Reputation: 1713

I'm not entirely sure, but it kinda sounds like to me your problem lies in your model. Because each time your View loads it calls the makeNewButton() function right?

Maybe you can fix the problem by displaying the "new note" view and having an extra "Save" button that only makes changes to your model once it's triggered.

Alternatively, you could use context.rollback() to discard changes. Also, check out this Project. It's Beta 4 but works just the same and imo is a good example how to use CoreData with SwiftUI. :)

Upvotes: 1

Related Questions