blindowl
blindowl

Reputation: 33

Disable/enable NSMenu item

I've created a menu bar app, a NSMenu object using the Interface Builder (following this tutorial). The menu has two items:

Start Commando

Stop Commando

How can I disable/enable the menu items when they're clicked? I've set disabled "Auto Enables Items" and I can manually enable/disable the items in the Attributes inspector, but how can I achieve the same thing when their functions are called?

When "Start Commando" is clicked I want the item to disable and "Stop Commando" to enable. And the other way around when "Stop Commando" is clicked.

Upvotes: 3

Views: 3643

Answers (4)

empedocle
empedocle

Reputation: 1932

As others say, there is a isEnabled property for NSMenuItems. One also needs to uncheck Auto Enables Items for that menu or sub-menu in the Attributes Inspector in Xcode, or through code, to allow the setting to take effect.

enter image description here

To get it to change on selection, in the IBAction called for the menu item, likely in your NSWindowController, do something like this:

@IBAction private func myMenuAction(sender: NSMenuItem) {
     sender.isEnabled = false 
}

You will not be able to then select the menu item afterwards. I assume you re-enable it else where as so:

if let appDelegate = NSApplication.shared.delegate as? AppDelegate {
    appDelegate.myMenuItem.isEnabled = true
}

Code untested.

Upvotes: 1

user9359038
user9359038

Reputation:

You can try below code :

let menu = NSMenu();
menu.autoenablesItems = false

Upvotes: 2

Mukul More
Mukul More

Reputation: 564

Swift provides with setEnabled property that can be used on NSMenuItem you are trying to enable or disable.

You can do the following :

@IBOutlet weak var startMenuItem: NSMenuItem! 

startMenuItem.isEnabled = false or true

Upvotes: 2

Ferrakkem Bhuiyan
Ferrakkem Bhuiyan

Reputation: 2783

Declare a BOOL value for instance

BOOL isActive 

if(isActive)
{
   //show menu
}
else
{
   //hide your menu
}

also make BOOL true when your view dismiss

Upvotes: 0

Related Questions