首页 > 解决方案 > 不将新数据附加到数组

问题描述

我想将新数据添加到项目中的列表中,但我做不到

我有一个用于显示产品列表的 ContentView.swift 视图,在另一个视图(ShopView)中我想将数据添加到产品数组我的产品数组和 Products.swift 文件中的 addProduct() 函数

请帮助我谢谢

内容视图.swift

struct ContentView: View {
    @ObservedObject var cart = Products()
    
    var body: some View {
        NavigationView{
            List {
                ForEach(cart.products) { product in
                    Text("\(product.name) \(product.price)$")
                }
            }
            .navigationBarItems(
                trailing: NavigationLink(destination: Shop()) {
                    Text("Go Shop")
                })
            .navigationBarTitle("Cart")
        }
    }
}

产品.swift

struct Product: Identifiable {
    var id = UUID()
    var name: String
    var price: Int
}

Shop.swift

struct Shop: View {
    @ObservedObject var cart = Products()
    
    var body: some View {
        VStack{
            Button("Add Product To Cart") {
                cart.addProduct(product: Product(name: "Name", price: 399))
            }
        }
    }
}

Products.swift

class Products: ObservableObject {
    @Published var products = [Product]()
    
    func addProduct(product: Product) {
        products.append(product)
        print("Product Added")
    }
}

标签: swiftxcodelistswiftuiswiftui-list

解决方案


现在,您正在创建两个不同Products. 如果要共享数据,则必须使用相同的实例

struct ContentView: View {
    @ObservedObject var cart = Products()
    
    var body: some View {
        NavigationView{
            List {
                ForEach(cart.products) { product in
                    Text("\(product.name) \(product.price)$")
                }
            }
            .navigationBarItems(
                trailing: NavigationLink(destination: Shop(cart: cart)) {  //<-- HERE
                    Text("Go Shop")
                })
            .navigationBarTitle("Cart")
        }
    }
}


struct Shop: View {
    @ObservedObject var cart : Products //<-- HERE
    
    var body: some View {
        VStack{
            Button("Add Product To Cart") {
                cart.addProduct(product: Product(name: "Name", price: 399))
            }
        }
    }
}

实现此类功能的另一种方法是使用环境对象。有关该方法的补充阅读:https ://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views


推荐阅读