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.

1
  • It's a good workaround, check this answer. Commented May 18, 2021 at 14:59

1 Answer 1

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")
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.