简体   繁体   中英

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.

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 .

Answer can be found here: validateMenuItem or menuWillOpen not called for NSMenu

validateMenuItem: belongs to the NSMenuValidation informal protocol; for it to be called the relevant menu items must have a target .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM