I have list of (several) products in cart. Each product has it's corresponding view created from generic view by passing product's object. View of single product in cart has two button (+ and -) to control the amount of the product in cart. Unfortunately, when products views are embedded in List (and then ForEach) these two buttons do not work because clicking on the whole product view leads to another detailed view (which I want to leave as it is). I need ForEach to be embedded in List because I want to use .onDelete modifier to easily delete the products from list. What I want is those two buttons (+ and -) work.
List View:
List {
ForEach(Array(cartViewModel.cart.products.keys).sorted { $0.id > $1.id}, id: \.self) { product in
ProductTileForCartView(product: product)
.environmentObject(cartViewModel)
.onTapGesture {
withAnimation(.interactiveSpring(response: 0.6, dampingFraction: 0.7, blendDuration: 0.7)) {
cartViewModel.changeFocusedProductFor(product: product)
}
}
}
.onDelete(perform: cartViewModel.removeProducts)
}
SingleProductView:
HStack(alignment: .center) {
KFImage(URL(string: product.imagesURLs.first!)!)
.placeholder {
Image("product_placeholder_image")
.resizable()
.aspectRatio(contentMode: .fit)
.clipShape(RoundedRectangle(cornerRadius: 15))
}
.retry(maxCount: 3, interval: .seconds(3))
.cancelOnDisappear(true)
.resizable()
.aspectRatio(contentMode: .fit)
.clipShape(RoundedRectangle(cornerRadius: 15))
.padding([.vertical, .trailing])
VStack(alignment: .leading) {
VStack(alignment: .leading, spacing: 10) {
Text(product.company)
.font(.system(size: 14, weight: .regular, design: .rounded))
.foregroundColor(.gray)
.fixedSize(horizontal: false, vertical: true)
Text(product.name)
.font(.system(size: 22, weight: .heavy, design: .rounded))
.fixedSize(horizontal: false, vertical: true)
.foregroundColor(colorScheme == .light ? .black : .white)
Text("$\(product.price, specifier: "%.2f")")
.font(.system(size: 20, weight: .bold, design: .rounded))
.foregroundColor(.accentColor)
}
Spacer()
if includeButtonsForAmountChange {
HStack(spacing: 20) {
Button {
withAnimation {
cartViewModel.removeProductFromCart(product: product, quantity: 1)
}
} label: {
Image(systemName: "minus.square.fill")
.resizable()
.frame(width: 30, height: 30)
}
Text("\(cartViewModel.getCartProductCount(product: product))")
.font(.system(size: 22, weight: .heavy, design: .rounded))
Button {
withAnimation {
cartViewModel.addProductToCart(product: product, quantity: 1)
}
} label: {
Image(systemName: "plus.square.fill")
.resizable()
.frame(width: 30, height: 30)
}
}
}
}
.padding()
}