How to get current CoreData item in onDelete

前端 未结 1 1762
攒了一身酷
攒了一身酷 2021-01-26 19:08

There two entities Parent and Child, which is one to many relationship. One Parent and many Child.

I use EditMode to delete

相关标签:
1条回答
  • 2021-01-26 19:21

    Here is possible approach... (assuming your .loadDB returns array, but in general similar will work with any random access collection)

    Tested with Xcode 11.4 (using regular array of items)

    var body: some View {
        VStack {
            Form {
                Section(header: Text("Title")) {
                    // separate to standalone function...
                    self.sectionContent(with: db.loadDB(relatedTo: parent))
                }
            }
        }
    }
    
    // ... to have access to shown container
    private func sectionContent(with children: [Child]) -> some View {
        // now we have access to children container in internal closures
        ForEach(children) { child in
    
            if self.editMode == .active {
                ChildListCell(name: child.name, order: child.order)
            } else {
                ...
            }
        }
        .onDelete { indices in
    
            // children, indices, and child by index are all valid here
            if let first = indices.first {
                let thisChild = children[first]       // << here !!
                // do something here
            }
    
            self.db.deleting(at: indices)
        }
    }
    
    0 讨论(0)
提交回复
热议问题