Delete From List When Tapped SwiftUI

Viewed 462

I want to delete an item from the list when the item is tapped. When I delete one of the cells all the rest of the cell tap indicators are showing that they are tapped too.

Plus it does not delete it just makes it temporarily invisible. When I reload the page deleted cells are again in the memory and visible again.

List{
                ForEach(list.reminders, id: \.self) { reminder in
                    Button(action: {
                        self.isSelected.toggle()
                        self.delete(at: list.reminders.firstIndex(where: {$0.hashValue == reminder.hashValue})!)
                    }, label: {
                        HStack{
                            Image(systemName: isSelected ? "largecircle.fill.circle" : "circle")
                                .resizable()
                                .aspectRatio(contentMode: .fit)
                                .foregroundColor((isSelected ? Color(list.color) : .gray))
                                .frame(width: 22, height: 22, alignment: .trailing)
                                .cornerRadius(22)
                            ReminderCell(reminder: reminder)
                        }
                    })
                    .padding(.bottom)
                }.onDelete(perform: deleteReminder)
            }

func deleteReminder(at offsets: IndexSet) {
    list.reminders.remove(atOffsets: offsets)
}
func delete(at index: Int) {
    list.reminders.remove(at: index)
}
1 Answers

First, If you want to make the function in .onTapGesture {} work, you have to put it outside Button label, because when you tap it, the function in Button action will be triggered.

Second, if you want to get index of element in ForEach, you have to add indices. Check my code below, because you don't post your code completely, I can't test my code exactly.

        List {
            ForEach(list.reminders.indices, id: \.self) { index in
                HStack {
                    Button(action: {
                        self.isSelected.toggle()
                    }, label: {
                        Image(systemName: isSelected ? "largecircle.fill.circle" : "circle")
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .foregroundColor((isSelected ? Color(list.color) : .gray))
                            .frame(width: 22, height: 22, alignment: .trailing)
                            .cornerRadius(22)
                    })
                    Button(action: {
                        deleteReminder(at: IndexSet(integer: index))
                    }) {
                        ReminderCell(reminder: list.reminders[index])
                    }
                }
                .padding(.bottom)
            }.onDelete(perform: deleteReminder)
        }

Related