I am trying to create custom menu items in SwiftUI app for macOS (SwiftUI App life cycle). I don't quite understand the following behaviour:
In the trivial code below:
the buttons added via CommandMenu behave as expected (i.e. activate and deactivate according to the changing value of 'active'. The buttons added via CommandGroup get correctly configured according to the value of 'active' at launch, but ignore the changes of 'active' and don't change their state. What am I missing?
In the trivial code below:
Code Block import SwiftUI @main struct MenuTestApp: App { @State var active = false var body: some Scene { WindowGroup { ContentView() } .commands(content: { CommandMenu("Tools", content: { Button("Normally active", action: {active = !active}).disabled(active) Button("Normally inactive", action: {active = !active}).disabled(!active) }) CommandGroup(after: .newItem, addition: { Button("Normally active", action: {active = !active}).disabled(active) Button("Normally inactive", action: {active = !active}).disabled(!active) }) }) } }
the buttons added via CommandMenu behave as expected (i.e. activate and deactivate according to the changing value of 'active'. The buttons added via CommandGroup get correctly configured according to the value of 'active' at launch, but ignore the changes of 'active' and don't change their state. What am I missing?
Thanks!
It is working indeed.
Whatever the root cause of the problem is, it is not just the @State variables. Originally I ran into this issue when I was using either @ObservedObject or @StateObject and the boolean controlling the button state would be @Published in the corresponding class. I wrote the example posted here just to simplify the case and focus on the problem.
It is working indeed.
Whatever the root cause of the problem is, it is not just the @State variables. Originally I ran into this issue when I was using either @ObservedObject or @StateObject and the boolean controlling the button state would be @Published in the corresponding class. I wrote the example posted here just to simplify the case and focus on the problem.