Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validateMenuItem not called for every menu item

I have main menu that has several menu items (File, Edit, View, Window - and more). All menu items have their action set to an operation in FirstResponder.

The application has a single window and that window is of the type MyWindow that inherits from NSWindow (see below).

Note that NSWindow implements NSMenuValidation and hence it is flagged as an error when MyWindow would declare conformance to NSMenuValidation.

I have overriden the function validateMenuItem as follows:

class MyWindow: NSWindow, NSMenuDelegate {

    ...

    override func validateMenuItem(_ item: NSMenuItem) -> Bool {
        Log.atDebug?.log("\(item.title)")
        ....
    }
}

When I run the application the validateMenuItem function is called for the File and the Window menu items but not for the Edit and View items.

Note: Log is an instance of a logging framework (SwifterLog).

The actions for all menu items are called correctly. (Also for the menu items for which the validateMenuItem is not called)

It is not difficult for me to work around this problem (the function menuNeedsUpdate is called for all menu's and can be used for this), but I would like to know why this behaviour occurs.

like image 552
BalancingRock Avatar asked Oct 17 '25 18:10

BalancingRock


1 Answers

This is not an answer, but to anyone interested in a work-around:

@objc func menuNeedsUpdate(_ menu: NSMenu) {

    Log.atDebug?.log("\(menu.title)")

    ...    // do other stuff    

    menu.items.forEach( { $0.isEnabled = validateMenuItem($0) } )
}

You must als set the delegate of each menu that must be handled to the MyWindow object (in this example). In my example, the menu of the menu item View must have its delegate set to MyWindow.

like image 75
BalancingRock Avatar answered Oct 20 '25 08:10

BalancingRock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!