简体   繁体   English

无法使用 @EnvironmentObject SwiftUI 更新先前视图上的文本

[英]Can't Update Text on Previous View using @EnvironmentObject SwiftUI

i'm new in SwiftUI.我是 SwiftUI 的新手。 So, I am doing my practice and create some kind of cashier app and here I been stuck for a while.所以,我正在练习并创建某种收银应用程序,在这里我被困了一段时间。 In ProductPageView I can increase and decrease the number of item.ProductPageView我可以增加和减少项目的数量。 Then, when I go to DetailOrderView (like a cart view), I can also increase and decrease the quantity number.然后,当我 go 到DetailOrderView (就像购物车视图)时,我也可以增加和减少数量。 The print shows the quantity number correctly.印刷品正确显示数量。 But if I go back to ProductPageView , the label doesn't update it self.但是,如果我 go 回到ProductPageView ,则 label 不会自行更新。

Take a look at this screenshots:看看这个截图:

First, I add 2 items.首先,我添加 2 个项目。

在此处输入图像描述

Then I go to DetailOrderView , the quantity number is the same.:然后我 go 到DetailOrderView ,数量相同:

在此处输入图像描述

Then I add 2 items in DetailOrderView (so it's now 4 items) and going back to ProductPageView , notice how the total price has increased but the quantity doesn't change.然后我在DetailOrderView中添加 2 个项目(所以现在是 4 个项目)并返回到ProductPageView ,注意总价格如何增加但数量没有变化。 I feel like I want to "refresh" or "reload data" on this page.我觉得我想在此页面上“刷新”或“重新加载数据”。

在此处输入图像描述

How can I fix this and update the Text when I press the back button?当我按下后退按钮时,如何解决这个问题并更新文本?

Here's my code:这是我的代码:

Main主要的

import SwiftUI

@main
struct CashierApp: App {
    @StateObject var productOder = ProductPresenter()

var body: some Scene {
    WindowGroup {
        MainPageView()
            .environmentObject(productOder)
    }
}

} }

Product Page View import SwiftUI产品页面查看进口SwiftUI

struct ProductPageView: View {
    @EnvironmentObject var productOrder: ProductPresenter


var body: some View {
    VStack {
        ScrollView {
            VStack {
                ForEach(productOrder.cartItems, id: \.item.idItem) { element in
                    ProductRow(cartItems: CartItems(item: element.item, quantity: element.quantity))
                }
            }
        }
        TotalPaymentRow()
    }
}

} }

Detail Order View or Cart View import SwiftUI详细订单视图或购物车视图导入 SwiftUI

struct DetailOrderView: View {
    @EnvironmentObject var productOrder: ProductPresenter
    var arrayOrdered: [CartItems] = []


var body: some View {
    
    ZStack {
        ScrollView {
            VStack {
                ForEach(arrayOrdered, id: \.item.idItem) { element in
                    ProductRow(cartItems: CartItems(item: element.item, quantity: element.quantity))
                }
            }
            .padding(.top, 10)
        }
        CustomModalGrandTotal()
    }
    .navigationTitle("Cart")
    .navigationBarTitleDisplayMode(.inline)
}

} }

The Presenter主持人

import SwiftUI
import Combine

class ProductPresenter: ObservableObject {
     @Published var cartItems: [CartItems] = []
     var totalQuantity = 0

     // Increment product
     func increment(cartItem: inout CartItems) {
         let index: Int = cartItems.firstIndex(where: {$0.item == cartItem.item}) ?? -1
         cartItems[index].quantity += 1
         totalQuantity += 1
     }

     // Decrement product
     func decrement(cartItem: inout CartItems) {
         let index: Int = cartItems.firstIndex(where: {$0.item == cartItem.item}) ?? -1
         if cartItems[index].quantity > 0 {
             cartItems[index].quantity -= 1
             totalQuantity -= 1
         }
     }
}

Product Row产品行

import SwiftUI

struct ProductRow: View {
    @State var cartItems: CartItems
    @EnvironmentObject var productOrder: ProductPresenter

var body: some View {
    
    HStack(alignment: .center) {
        Image(cartItems.item.image ?? "")
        VStack(alignment: .leading, spacing: 8) {
            Text(cartItems.item.name ?? "")
            Text(getPrice(value: cartItems.item.price ?? 0))
        }
        Spacer()
        VStack {
            Spacer()
            HStack{
                Button(action: {
                    if cartItems.quantity > 0 {
                        cartItems.quantity -= 1
                        productOrder.decrement(cartItem: &cartItems)
                        productOrder.calculateTotalPrice()
                    }
                }, label: {
                    imageMinusPlus(name: "minus")
                })
                Text("\(cartItems.quantity)") // This Text should be updated.
                Button(action: {
                    cartItems.quantity += 1
                    productOrder.increment(cartItem: &cartItems)
                    productOrder.calculateTotalPrice()
                }, label: {
                    imageMinusPlus(name: "plus")
                })
            }
        }
    }
}
}

PS: I deleted the styling to make the code shorter. PS:我删除了样式以使代码更短。

Thankyou in advance先感谢您

Besides passing "ProductPresenter" instance around as "environment" object (which you are handling correctly) you need to declare your properties as @Published, as in this case for "totalQuantity", which now updates the total overall quantity.除了将“ProductPresenter”实例作为“环境”object(您正在正确处理)传递之外,您还需要将您的属性声明为@Published,如本例中的“totalQuantity”,它现在会更新总量。

class ProductPresenter: ObservableObject {
   @Published var cartItems: [CartItems] = [
      CartItems(item: CartItems.Item(image: "system.car", name: "My item", price: 10, idItem: UUID()), quantity: 3)
   ]
   @Published var totalQuantity = 0 
}

But this doesnt solve this line:但这并不能解决这一行:

Text("\(cartItems.quantity)") // This Text should be updated.

for following reasons:出于以下原因:

  • your model (CartItems) has to be a class type and conform to ObservableObject protocol您的 model (CartItems) 必须是 class 类型并符合 ObservableObject 协议
  • your property has to be set using @Published.您的属性必须使用@Published 设置。

I think productOrder need to be defined as ObservableObject with @Published properties and int this case it need to be class not a structure, for example:我认为 productOrder 需要定义为具有 @Published 属性的 ObservableObject 并且在这种情况下它需要是 class 而不是结构,例如:

import SwiftUI
import Combine

final class ProductOder: ObservableObject {
    @Published var cartItems: [CartItem] = []
    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM