The above answers did not help me to solve my problem. I have created a separate project to understand when the validateMenuItem(:)
method is called.
The validateMenuItem(:)
method will be called only if:
- Conform to
NSMenuItemValidation
in the class which implements the NSPopUpButton
.
- All NSMenuItems must have an action and target set to the object which implements the
NSMenuItemValidation
protocol.
- Implement the
validateMenuItem(:
) method.
- Implement the
dummyAction(:)
method for NSMenuItem which doesn't do anything.
- The NSPopUpButton "Items: Autoenables" autoenablesItems must be set
Version 11.5 (11E608c) , Swift 5.0, DP: macOS 10.15.
Code:
import Cocoa
// 1) Conform to NSMenuItemValidation in the class which implements the NSPopUpButton.
class NSMenuItemValidationTestViewController: NSViewController, NSMenuItemValidation {
@IBOutlet weak var popupButton: NSPopUpButton!
// MARK: - ViewController lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// .target and .action are set programmatically because menus are mostly build programmatically.
// 2) All NSMenuItems must have an action and target set to the object which implements the
// NSMenuItemValidation protocol.
self.popupButton?.menu?.items.forEach{( $0.target = self )}
self.popupButton?.menu?.items.forEach{( $0.action = #selector(dummyAction(_:)) )}
}
// MARK: - NSMenuItemValidation
// 3) Implement the validateMenuItem(:) method.
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
print("Function: \(#function), line: \(#line)")
return true
}
// 4) Implement the dummyAction(:) method for NSMenuItem which doesn't do anything
@IBAction func dummyAction(_ sender: NSMenuItem?) {
print("Function: \(#function), line: \(#line)") }
}
// 5) The NSPopUpButton "Items: Autoenables" checkbox must be set to true in storyboard.
// or
// self.popupButton?.menu?.autoenablesItems = true
TODO: Github link to source code. (Coming soon).
validateMenuItem:
method was not to be called. (Frustrating... given that I was struggling with it 2 hours before posting it in SO (and then answering it myself after 10 minutes... lol)) – Coshow