I would like to implement NSMenuItem
to trigger certain functionality (e.g. "Run Calculation"). How do I access the menu items in order to enable/disable the items based on the app logic? E.g. the "cut" function for text is only enable as menu item when test is selected. "Run Calculation" should only get enabled when certain criteria are given.
Thanks!
Asked
Active
Viewed 1,394 times
4

JFS
- 2,992
- 3
- 37
- 48
-
`NSMenuItem` conforms to `NSValidatedUserInterfaceItem` which works with the `NSUserInterfaceValidations` protocol. Implement `func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool`. See [User Interface Validation](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/UIValidation/UIValidation.html#//apple_ref/doc/uid/10000040i). – Willeke Feb 25 '19 at 21:09
1 Answers
12
You probably have some view controller or window controller that implements runCalculation
, like this:
class ViewController: NSViewController {
@IBAction func runCalculation(_ sender: Any?) {
print(1 + 1)
}
}
And you have connected the “Run Calculation” menu item's action to the runCalculation
method of the controller.
To enable and disable the menu item, follow these steps:
Make sure the “Calculator” menu itself (of type
NSMenu
) has the “Auto Enables Items” property turned on in IB, or hasautoenablesItems
set to true in code.Make your controller conform to the
NSUserInterfaceValidations
protocol:extension ViewController: NSUserInterfaceValidations { func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool { // See step 3... return true } }
In
validateUserInterfaceItem
, check whether the item'saction
isrunCalculation(_:)
. If so, return true if and only if you want to allow the user to run the calculation:extension ViewController: NSUserInterfaceValidations { func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool { switch item.action { case #selector(runCalculation(_:))?: // Put your real test here. return !textField.stringValue.isEmpty default: return true } } }

rob mayoff
- 375,296
- 67
- 796
- 848
-
Thanks a lot for the details. Its the first time I deal with NSMenu. You helped me a lot! – JFS Feb 25 '19 at 21:23