Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
            }
        }
    }
    
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!