1

I am implementing a custom delete button, without using List and .onDelete, however I can't seem to get the IndexSet of the row and couldn't find example of this anywhere.

CartView.swift

struct CartView: View {
    @ObservedObject var cartListVM = CartListViewModel()
    
    func deleteCart(at offsets: IndexSet) {
        offsets.forEach { index in
            let cart = cartListVM.carts[index]
            cartListVM.delete(cart)
        }
        cartListVM.getAllcarts()
    }

    var body: some View {
        VStack {
            ForEach(cartListVM.carts, id: \.id) { c in
                VStack {
                    Text(c.menuName)
                    Button(action: {
                        deleteCart(at: indexSet)
                        // Can't seem to get the IndexSet here, how?
                    }) {
                        Text("Delete")
                    }
                }
            }
        }
    }
}

How do I get the indexset of the row? Thank you in advance.

Charas
  • 1,753
  • 4
  • 21
  • 53

1 Answers1

0

Try looping over the indices instead of the carts, so you can access each index. Then, just use remove(at:) to remove.

ForEach(cartListVM.carts.indices, id: \.self) { index in
    VStack {
        Text(cartListVM.carts[index].menuName)
        Button(action: {
            cartListVM.carts.remove(at: index)
        }) {
            Text("Delete")
        }
    }
}
aheze
  • 24,434
  • 8
  • 68
  • 125