Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

210
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda