Search code examples
swiftenvironment-variablesglobal-variablesswiftui

@EnvironmentObject in SwiftUI - can't toggle bool


I have the class below to keep the state of the hamburger menu if it is or not displayed

class Menu: ObservableObject {
    @Published var isActive: Bool = false
}

I instantiate it in Scene Delegate as such

let contentView = ContentView().environmentObject(Menu())

Then in a simple view i am trying to toggle the isActive bool, however i get the error below

struct Button: View {

    @EnvironmentObject var menuState: Menu

    var body: some View {

        VStack{

            Button(action: {
                self.menuState.isActive.toggle()
            }) {
                Text("A")
            }
        }

    }
}

This is the error i get: Cannot invoke initializer for type 'Button' with an argument list of type '(action: @escaping () -> (), @escaping () -> Text)'


Solution

  • The issue is that you named your custom View as Button, which is also the name of the existing SwiftUI button.

    Simply rename your struct to something else and your code will compile just fine.

    Unrelated to your question, but there's no point in wrapping a single View in a VStack, your body can simply contain the Button.

    struct MyButton: View {
    
        @EnvironmentObject var menuState: Menu
    
        var body: some View {
            Button(action: {
                self.menuState.isActive.toggle()
            }) {
                Text("A")
            }
        }
    }