@Published 字符串变量不更新视图

时间:2021-04-07 09:14:48

标签: ios swift xcode swiftui observableobject

我在 Observableobejct 中的@Published 字符串变量没有以某种方式更新文本。

完全相同的代码在不同的视图中工作,但我不明白为什么这在这个视图中不起作用。

当我在 Google 上搜索时,我发现的只是检查 observableobject 的初始化,将 didSet 设置为变量,但所有这些都不起作用,我只是恢复了。

以下是当 viewdidappear() 中的字符串更改时不更新视图的代码。

struct StorageUpgradeView: View {
    @ObservedObject private var storagevm = StorageVM()

    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        ZStack {
            VStack {
                ZStack(alignment: .center) {
                    HStack {
                        Button(action: {
                            presentationMode.wrappedValue.dismiss()
                        }, label: {
                            Image("Image_arrowleft")
                                .resizable()
                                .frame(width: 30, height: 30, alignment: .leading)
                        })
                    
                        Spacer()
                    }
                
                    Text("Storage Upgrade".localized)
                        .font(.system(size: 24))
                }
                .padding()
            
                Text(storagevm.month_price)
            
                Text("\(storagevm.halfyear_price)")
            
                Spacer()
            }
        }
        .onAppear(perform: {
            storagevm.viewdidappear()
        })
    
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .foregroundColor(Color("Theme_OnSurface"))
        .background(Color("Theme_Surface").ignoresSafeArea())
    }
}

class StorageVM: ObservableObject {
    @Published var month_price = "plpl"
    @Published var halfyear_price: String

    init() {
        halfyear_price = "asdf"
    }

    func viewdidappear() {
        month_price = "BlahBlah"
        halfyear_price = "were"
    }
}

但是当我通过更改标签来切换视图时,视图打印得很好。这里有什么问题?经过两天的谷歌搜索和敲我的头后,我无法弄清楚。

2 个答案:

答案 0 :(得分:0)

每当你想观察一个@Published 属性时,你都想在元素前使用 $ 符号。所以尝试使用 Text(storagevm.$month_price)

答案 1 :(得分:0)

使用 StateObject 而不是 ObservedObject 对我来说效果很好!请确保您的 iOS 目标需要 14.0 或更高版本才能使此解决方案起作用。