SWIFTUI 在所有三个视图中增加一个产品的数量

问题描述 投票:0回答:2

我需要单击 + 或 - 按钮并更改数量,问题是使用此代码数量总是重置为零, 我无法增加它并记住它,我还尝试在每个视图的每个按钮中使用 product.quantity += 1 ,但那时 HOME 工作但如果我从 CART 更改数量然后它不会更新它家。 而如果我将 product.quantity 放在 addTo Cart 函数中,它会告诉我请帮助我我尝试了所有方法“(变异运算符的左侧不可变:'product' 是一个'let'常量)” 在每个视图中,我想更改数量并在两个视图中更新 我也只需要将一件商品添加到购物车中,但由于我无法读取数量,所以我还是添加了更多

我附上HOME和CART的图片 enter image description here enter image description here

struct Product: Identifiable,Hashable {
    var id = UUID().uuidString
    var categoria: ProductType
    var codice: String
    var descrizione: String = ""
    var prezzo: String
    var immagine: String = ""
    var quantity: Int = 1
}
class SharedDataModel: ObservableObject {
    
    @Published var cartProducts: [Product] = []
    
    func addToCart(product: Product) {
        if let index = cartProducts.firstIndex(of: product) {
            cartProducts[index].quantity += 1 //it doesn't register the quantity for me and it always resets it to zero
        }else {
            cartProducts.append(product)
        }
    }

    func removeFromCart(product: Product) {
        guard let index = cartProducts.firstIndex(of: product) else {return}
        if cartProducts[index].quantity > 1 {
            cartProducts[index].quantity -= 1
        }else {
            cartProducts.remove(at: index)
        }
    }
struct ProductCardView: View{
    
    @Binding var product: Product
    @EnvironmentObject var sharedData: SharedDataModel
    
    var body: some View{

                Button (action: {
                    sharedData.removeFromCart(product: product)
                } , label: {
                    Image(systemName: "minus")
                        .frame(width: 25, height: 30)
                        .foregroundColor(.black)
                })
                Text("\(product.quantity-1)") //here i need to read the current quantity
                    .frame(width: 25, height: 30)
                Button(action: {
                    sharedData.addToCart(product: product)
                } , label: {
                    Image(systemName: "plus")
                        .frame(width: 25, height: 30)
                        .foregroundColor(.black)
                })
    }
}
struct CardView: View{

    @Binding var product: Product
    @EnvironmentObject var sharedData: SharedDataModel
 
                    Button {
                    sharedData.removeFromCart(product: product)
                    } label: {
                        Image(systemName: "minus")
                            .font(.caption)
                            .foregroundColor(.white)
                            .frame(width: 20, height: 20)
                            .background(Color("Quantity"))
                            .cornerRadius(4)
                    }

                    Text("\(product.quantita)")//here i need to read the current quantity
                        .font(.custom(customFont, size: 14))
                        .fontWeight(.semibold)
                        .foregroundColor(.black)
                    
                    Button {
                    sharedData.addToCart(product: product)
                    } label: {
                        Image(systemName: "plus")
                            .font(.caption)
                            .foregroundColor(.white)
                            .frame(width: 20, height: 20)
                            .background(Color("Quantity"))
                            .cornerRadius(4)
    }
}

我真的需要你的帮助,我都试过了,非常感谢你

swift swiftui product cart product-quantity
2个回答
0
投票

我写了一个小例子来构建类似的场景。我能够更新个别产品的数量。让我知道是否有帮助!

import SwiftUI

struct Product: Identifiable {
    let id = UUID()
    let title: String
    var quantity: Int
}

class StoreModel: ObservableObject {
    
    @Published var cartProducts: [Product] = []
    
    func populateProducts() {
        cartProducts = [Product(title: "Product 1", quantity: 0), Product(title: "Product 2", quantity: 0)]
    }
        
    func addToCart(_ product: Product) {
        
        guard let index = cartProducts.firstIndex(where: { p in
            p.id == product.id
        }) else { return }
        
        cartProducts[index].quantity += 1
    }
    
    func removeFromCart(_ product: Product) {
        
        guard let index = cartProducts.firstIndex(where: { p in
            p.id == product.id
        }) else { return }
                
        cartProducts[index].quantity -= 1
    }
    
}

struct ContentView: View {
    
    @EnvironmentObject private var storeModel: StoreModel
    
    var body: some View {
        List(storeModel.cartProducts) { product in
            HStack {
                Text(product.title)
                Button("+") {
                    storeModel.addToCart(product)
                }.buttonStyle(.borderedProminent)
                Button("-") {
                    storeModel.removeFromCart(product)
                }.buttonStyle(.borderedProminent)
                    .tint(.red)
                
                Text("\(product.quantity)")
            }
        }.task {
            storeModel.populateProducts()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .environmentObject(StoreModel())
    }
}

0
投票

非常感谢您的回复,我尝试复制粘贴您的代码添加一个视图,它总是在我更改视图后立即重置金额!!

import SwiftUI

struct Product: Identifiable {
    let id = UUID()
    let title: String
    var quantity: Int
}

class StoreModel: ObservableObject {
    
    @Published var cartProducts: [Product] = []
    
    func populateProducts() {
        cartProducts = [Product(title: "Product 1", quantity: 0), Product(title: "Product 2", quantity: 0)]
    }
        
    func addToCart(_ product: Product) {
        
        guard let index = cartProducts.firstIndex(where: { p in
            p.id == product.id
        }) else { return }
        
        cartProducts[index].quantity += 1
        
        print(cartProducts)
        print(product.quantity)
    }
    
    func removeFromCart(_ product: Product) {
        
        guard let index = cartProducts.firstIndex(where: { p in
            p.id == product.id
        }) else { return }
                
        cartProducts[index].quantity -= 1
    }
    
}

struct ContentView: View {
    
    @EnvironmentObject private var storeModel: StoreModel
    
    var body: some View {

        NavigationView {
            List(storeModel.cartProducts) { product in //Thread 1: Fatal error: No ObservableObject of type StoreModel found. A View.environmentObject(_:) for StoreModel may be missing as an ancestor of this view
                    HStack {
                        Text(product.title)
                        Button("+") {
                            storeModel.addToCart(product)
                        }.buttonStyle(.borderedProminent)
                        Button("-") {
                            storeModel.removeFromCart(product)
                        }.buttonStyle(.borderedProminent)
                            .tint(.red)
                        
                        Text("\(product.quantity)")
                    }
                }.task {
                    storeModel.populateProducts()
            }
                .navigationTitle(Text("Cart"))
                .toolbar {
                    NavigationLink{
                        Cart()
                            .environmentObject(StoreModel())
                    } label: {
                        Image(systemName: "cart")
                    }
                }
        }
    }
}

struct Cart: View {
    
    @EnvironmentObject private var storeModel: StoreModel
    
    var body: some View {

            List(storeModel.cartProducts) { product in
                HStack {
                    Text(product.title)
                    Button("+") {
                        storeModel.addToCart(product)
                    }.buttonStyle(.borderedProminent)
                    Button("-") {
                        storeModel.removeFromCart(product)
                    }.buttonStyle(.borderedProminent)
                        .tint(.red)
                    
                    Text("\(product.quantity)")
                    
                }
            }.task {
                storeModel.populateProducts()
            }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .environmentObject(StoreModel())
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.