2

I would like to en-/disable a Menu-Object programmatically in Swift. I found something one the Apple Developer Library: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSMenuItem_Class/#//apple_ref/occ/instp/NSMenuItem/enabled

But how to get a reference to the Menu-Object with the code and set its state programmatically?

3
  • 2
    Take a look at validateMenuItem:
    – vadian
    Commented May 29, 2016 at 18:11
  • @vadian Doesn't work
    – HelloToYou
    Commented May 30, 2016 at 16:25
  • Menu item validation is very powerful but also very sensitive. It depends on a few settings in Interface Builder and your design. If the menu is not in the responder chain you might connect the delegate of the menu (not the menu item) to the class which handles the validation.
    – vadian
    Commented May 30, 2016 at 16:32

4 Answers 4

6

For Swift 4+, some of the code in Barath's Answer has become deprecated. I also think the code is more adaptable by searching for menuitem titles rather than their index:

let mainMenu = NSApplication.shared.mainMenu!
let subMenu = mainMenu.item(withTitle: "Edit")?.submenu

subMenu?.item(withTitle: "Cut")?.isEnabled = false

Also, setting isEnabled to true or false will not toggle menu items as long as setAutoenablesItems is set to true. It can be disabled from the storyboard or programmatically.

4

Enable or Disable menu item without subclassing with the following code.

let mainMenu = NSApplication.sharedApplication().mainMenu!
let appMenu = mainMenu.itemAtIndex(0)!.submenu

appMenu?.itemWithTitle("Title")?.enabled = false
1

You can just set the enabled-attribute programmatically: menObj.enabled = false

14
  • How to get the Menu-Object to menObj now?
    – HelloToYou
    Commented May 29, 2016 at 18:15
  • If you made a Storyboard you can get the connection to the Menu-Object through an IBOutlet. Then you have easy-access to all attributes.
    – patreu22
    Commented May 29, 2016 at 18:36
  • Which subclass should the file have?
    – HelloToYou
    Commented May 29, 2016 at 18:47
  • Try to learn what IBOutlets are. Every UIView element is compatible. - Get a short video instruction: teamtreehouse.com/library/build-a-simple-iphone-app/…
    – patreu22
    Commented May 29, 2016 at 18:51
  • I'm able to create a connection to AppDelegate, but not to the Controller I'm needing.
    – HelloToYou
    Commented May 29, 2016 at 19:50
0

Simple Solution with Swift 5+

hamburgerMenuItem.isEnabled = false

Not the answer you're looking for? Browse other questions tagged or ask your own question.