Reputation: 636
struct ACFTHistory: View { @Environment(.managedObjectContext) var moc @FetchRequest(entity: ACFTScores.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \ACFTScores.createdAt, ascending: false)]) var acftScores: FetchedResults
@State var isPresented = false
@State private var showingDeleteAlert = false
var body: some View {
NavigationView {
List {
Section(header: Text("ACFT History")) {
ForEach(acftScores, id: \.id) { score in
ACFTHistoryView(createdAt: "\(score.createdAt ?? Date())", totalScore: score.totalScore ?? "0")
.foregroundColor(.white)
}.onDelete(perform: delete)
}.alert(isPresented: $showingDeleteAlert) {
Alert(title: Text("Delete Score"), message: Text("Delete Recore Permanently?"), primaryButton: .destructive(Text("Delete")) {
This is where I put the @State property to trigger my conditional, worked but it was buggy.
}, secondaryButton: .cancel())
}
}.navigationBarTitle(Text("ACFT Scoreboard"))
.navigationBarItems(trailing: EditButton())
}
}
func delete(at offsets: IndexSet) {
self.showingDeleteAlert = true
I tried to put a conditional with another @State property. I was able to delete the record but it throws errors and is glitchy.
for index in offsets {
let score = acftScores[index]
moc.delete(score)
do {
try self.moc.save()
} catch {
print(error)
}
}
}
Upvotes: 2
Views: 768
Reputation: 11539
Tou may consider add an extra state value :
@State var offsets: IndexSet?
var body: some View {
NavigationView {
List {
Section(header: Text("ACFT History")) {
ForEach(acftScores, id: \.id) { score in
ACFTHistoryView(createdAt: "\(score.createdAt ?? Date())", totalScore: score.totalScore ?? "0")
.foregroundColor(.white)
}.onDelete (perform: delete)
}
}
.navigationBarTitle(Text("ACFT Scoreboard"))
.navigationBarItems(trailing: EditButton()).alert(isPresented: self.$showingDeleteAlert){
Alert(title: Text("Delete Score"), message: Text("Delete Recore Permanently?"), primaryButton: .destructive(Text("Delete")) {
if let offsets = self.offsets{
for index in offsets {
let score = acftScores[index]
moc.delete(score)
do {
try self.moc.save()
} catch {
print(error)
}
}
}
}, secondaryButton: .cancel())}
}
}
func delete(at offsets: IndexSet) {
self.showingDeleteAlert = true
self.offsets = offsets
}
Upvotes: 1