Search code examples
core-dataswiftui

Deleting CoreData without onDelete in SwiftUI


my app shows CoreData as following in VStack. List isn't possible due to ScrollView.

 VStack (spacing: 20) {
    ForEach(groups) { group in
        NavigationLink(destination: GroupView()) {
            ZStack (alignment: .bottomLeading) {
            
            Image(uiImage: (UIImage(data: group.groupThumbnail ?? self.image) ?? UIImage(named: "defaultGroupThumbnail"))!)
                .resizable(capInsets: EdgeInsets())
                .aspectRatio(contentMode: .fill)
                .frame(height: 200, alignment: .center)
                .cornerRadius(22)
            
            VStack (alignment: .leading) {
                
                Text("\(group.groupTitle ?? "Untitled")")
                    .font(.title)
                    .fontWeight(.heavy)
                    .multilineTextAlignment(.leading)
                
                Text("Consists of 5 Flowers")
            }
            .padding([.leading, .bottom], 18.0)
            .foregroundColor(.primary)
        }

However, I can delete my entries with onDelete. Therefore, I am trying to find an alternative with .contextMenu.

.contextMenu {
    Button (role: .destructive) {
        withAnimation {
            self.deleteGroups(at: IndexSet.init(arrayLiteral: 0)) // This is the code I copied from the video.
        }
    } label: {
        Label("Delete", systemImage: "trash")
    }
    Button {
        print()
    } label: {
        Label("Edit", systemImage: "square.and.pencil")
    }

}

I saw a video in which somebody was able to delete his entry with the combination of these to codes When tapping on "Delete", the entry should be deleted by this code:

func deleteGroups(at offsets: IndexSet) {
        for offset in offsets {
            let group = groups[offset]
            viewContext.delete(group)
        }
        //try? viewContext.save()
    }

But, whenever I click this "Delete" Button in context menu, the wrong one gets deleted. I can't get the code to delete the selected entry. If anyone can help me, that would be appreciated. Thanks in Advance!

Not that important but, is there a delete feature compared to "onDelete" (such as swiping to delete) I can still implement? And are there any possibilities for animation in my case?

Kind Regards


Solution

  • Just delete it in the normal way:

    Button (role: .destructive) {
        withAnimation {
            viewContext.delete(group)
            do {
                try viewContext.save()
            } catch {
                // show error
            }
        }
    } label: {
        Label("Delete", systemImage: "trash")
    }
    

    FYI I also edited your question to fix your ForEach syntax.