Reputation: 33
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
Reputation: 1932
As others say, there is a isEnabled
property for NSMenuItem
s. 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.
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
Reputation:
You can try below code :
let menu = NSMenu();
menu.autoenablesItems = false
Upvotes: 2
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
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