skip to Main Content

My @Published string variable in Observableobejct does not update the Text somehow.

Exact same codes works in different view, but I can’t figure out why this isn’t working in this view.

When I searched Google all I figured out was about checking the initialization of observableobject, setting didSet to variable, but all of them did not work and I just reverted back.

The below is the code that does NOT update the view when string changes in 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"
    }
}

But view prints just well when I switch the view by changing tabs. What is the problem here? I couldn’t figure out after two days of googling and banging my head.

2

Answers


  1. Chosen as BEST ANSWER

    Using StateObject instead of ObservedObject worked well for me! Be sure that your iOS target needs to be 14.0 or higher for this solution to work.


  2. Whenever you want to observe a @Published attribute, you want to use the $ sign before the element. So try using Text(storagevm.$month_price)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search