swiftui delete row in Table

Viewed 36

I need some help with a strange behavior in Apple's new Table view (since macOS 12).

Table(diagnoses, sortOrder: $diagnoses.sortDescriptors) {
    TableColumn("ICD10", value: \.icd!) { dia in
        Text(dia.icd ?? "XXX.X")
    }
    .width(min: 30, ideal: 40, max: 50)
    TableColumn("diagnosis", value: \.diagnosis!) { dia in
        Text(dia.diagnosis ?? "notSpec")
    }
    TableColumn("gestellt", value: \.madeOn!) { dia in
        if dia.madeOn != nil {
            Text(Formatters.dateFormatter.string(from: dia.madeOn!))
        }
    }
    .width(min: 60, ideal: 70, max: 80)
    TableColumn("") { dia in
        HStack {
            Button(
                action: {
print(dia) // <<-- here correct "dia"
                    showDiaDelAlert.toggle()
                },
                label: {
                    Image(systemName: "trash")
                }
            )
            .buttonStyle(.borderless).foregroundColor(Color.accentColor)
            Button(
                action: {
                    showingDiaEditScreen.toggle()
                },
                label: {
                    Image(systemName: "pencil")
                }
            )
            .buttonStyle(.borderless).foregroundColor(Color.accentColor)
        }
        .confirmationDialog("alertDelete", isPresented: $showDiaDelAlert) {
            Button("ok", role: .destructive){
print(dia) // <<-- here other "dia". Mainly the first item in Table
                deleteItem(item: dia, moc: moc)
            }
            Button("cancel", role: .cancel) {
                showDiaDelAlert.toggle()
            }.keyboardShortcut(.defaultAction)
        }
        .sheet(isPresented: $showingDiaEditScreen) {
            EditDiagnosisView(diagno: dia)
        }
    }
    .width(min: 30, ideal: 40, max: 50)
}
.tableStyle(.bordered(alternatesRowBackgrounds: true))

Everything works fine so far. But with editing (showing sheet), and deleting there are some problems.

  • Editing: the form in the sheet doesn't display the right row and when closing the sheet, for every other row die sheet is displayed again.
  • Deleting: the wrong row is deleted, and the alert appears once again. Confirmation will delete the next / previous row, too.

I need to place buttons, because Table doesn't offer swipe actions (or?). And I need to place the .confirmationDialog and the .sheet somewhere within the TableColumn to get the dia.

Any ideas, what's wrong and how to solve this?

0 Answers
Related