View not update when published variable in class changes within the class

I have a struct that need to present some view when variable in class changes.

Example:

struct Example: View {
  @StateObject var isText = ProviderDelegate()
  var body: some View {
   Text("here some text")
    if(isText.show) {
       Bar()
    }
}

the providerDelegate:

class Adapter: ObservableObject {
  @Published public var show: Bool = false;
   
   func changeShow() {
       show.toggle()
   }
   ...
}

when function from other class to changeShow the View is not updation, thus the bar() is not shown.

Why is that?

Answered by BabyJ in 727712022

Where are you calling changeShow()?

The code you provided should work fine. Can you show some more code which would reveal the problem.


I tested with this code and tapping the "Text" showed and hid the "Bar" text.

var body: some View {
   Text("Text")
        .onTapGesture {
            isText.changeShow()
        }

    if isText.show {
       Text("Bar")
    }
}

mistake in the class. @StateObject var isText = Adapter()

Accepted Answer

Where are you calling changeShow()?

The code you provided should work fine. Can you show some more code which would reveal the problem.


I tested with this code and tapping the "Text" showed and hid the "Bar" text.

var body: some View {
   Text("Text")
        .onTapGesture {
            isText.changeShow()
        }

    if isText.show {
       Text("Bar")
    }
}