SwiftUI equivalent of validateMenuItem(_:)

I am wondering how to validate menu items in SwiftUI (2.0, macOS).

Given the following:

Code Block swift
@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .commands {
            CommandMenu("DEBUG") {
                Button(action: { }) {
                    Text("menu item 1")
                }
                Button(action: { }) {
                    Text("menu item 2")
                }
            }
        }
    }
}


Suppose menu item 1 is conditional and should be shown or hidden depending on the app state.

In AppKit we would use NSMenuItemValidation

Code Block swift
   func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
// validate the menuItem to be shown
}


to determine if a menu item should be shown/disable/enabled.

Question: how can we do menu validation in SwiftUI?

From what I have found so far CommandMenu is build *once* and cannot be dynamically adapted to reflect the current AppState. Or am I missing something?




Hi,

it seems @FocusedBinding and @FocusedValue can be used for that, though I have not tried it yet. Please see here, where it is discussed: https://developer.apple.com/forums/thread/651748 . (The last entry there by "Frameworks Engineer")

Cheers, Michael
Hi Michael,

Thanks for your reply.

I did find the post you refer to myself as well a couple of days ago. Actually I wanted to post this link myself, but I did not yet, as I did not get things working. The (extensive) code example the Apple engineer posted looks promising, but in my code I could not get it to work: I did notice that as soon as I set the focusValue, my app goes haywire: my codebase has some NSViewControllerRepresentable's and the update method is called endlessly as soon as the Focusvalue is set. This causes my app to show the spinner and become unresponsive. I suspect it is a bug, but I am not sure. I posted a bug report to Apple, hoping they will ever read and fix it. In the meantime, I keep trying myself and I am hoping someone on this forum might come up with some great solution.

While I am at it: I think the demo code is the way to go, but it raised an additional question for me: suppose one has an embedded AppKit outlineView (or whatever) and want to update menu, for example because. that outline view has the focus on some selected items: how to (best) use "focus value" from within appkit?


SwiftUI equivalent of validateMenuItem(_:)
 
 
Q