-3

I have some simplified code here for the purposes of debugging. I want to change the value of the isTrue variable inside SomeClass through ViewModel. The code below shows what I mean. When I run this program, and I press on the button, it does not update the button's label. It remains at "It's True," even though the value is indeed changing, according to the print statement. What's going on here? How can I fix this?

class SomeClass: ObservableObject {
    @Published var isTrue = true
}

class ViewModel: ObservableObject {
    @Published var someObject = SomeClass()
}

@main
struct NotWorkingApp: App {
    
    @StateObject private var vm = ViewModel()
    
    var body: some Scene {
        MenuBarExtra {
            SettingsLink()
        } label: {
            Text("Hello")
        }
        .menuBarExtraStyle(.window)
        
        Settings {
            SettingsView()
                .environmentObject(vm)
        }
    }
}

struct SettingsView: View {
    
    @EnvironmentObject var vm: ViewModel
    
    var body: some View {
        Button(vm.someObject.isTrue ? "It's True" : "It's False") { // Does not update when I press the button, although it does change the value.
            vm.someObject.isTrue.toggle()
            print(vm.someObject.isTrue)
        }
    }
}

MohAliBou
  • 47
  • 7

0 Answers0