swift - 不将新数据附加到数组
问题描述
我想将新数据添加到项目中的列表中,但我做不到
我有一个用于显示产品列表的 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")
}
}
解决方案
现在,您正在创建两个不同的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
推荐阅读
- haskell - 模式同义词作为函数的无趣/困惑
- r - 将具有日期时间列的数据框转换为 R 中的时间序列
- bash - golangci-lint 运行命令在 makefile 中显示错误
- android - 如何创建自定义视图充气器并将其设置为样式资源?
- python - 如果匹配字符串,熊猫删除行(不区分大小写)
- c++ - 为什么 t.join 在这个例子中不能被调用两次?
- python - “默认为用户安装,因为普通站点包不可写”python 消息
- javascript - 如何按类获取点击元素的索引?
- javascript - Google Firebase 网络应用程序登录页面
- arrays - 在结构/数组中存储和访问不同数据类型的变量/数组的正确方法