Search code examples
swiftxcodemacosnsmenuitem

Access Menu Item to Disable/Enable


I would like to implement NSMenuItemto 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!

enter image description here


Solution

  • 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:

    1. Make sure the “Calculator” menu itself (of type NSMenu) has the “Auto Enables Items” property turned on in IB, or has autoenablesItems set to true in code.

      menu auto enables items checkbox

    2. Make your controller conform to the NSUserInterfaceValidations protocol:

      extension ViewController: NSUserInterfaceValidations {
          func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
              // See step 3...
              return true
          }
      }
      
    3. In validateUserInterfaceItem, check whether the item's action is runCalculation(_:). 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
              }
          }
      }