onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
669 stars 33 forks source link

How to enable NSMenuItem in AppKit #428

Open onmyway133 opened 4 years ago

onmyway133 commented 4 years ago

Need to set target

let item = NSMenuItem(
    title: title,
    action: #selector(onMenuItemClicked(_:)),
    keyEquivalent: ""
)

item.target = self

Sometimes, need to check autoenablesItems

Indicates whether the menu automatically enables and disables its menu items.

This property contains a Boolean value, indicating whether the menu automatically enables and disables its menu items. If set to true, menu items of the menu are automatically enabled and disabled according to rules computed by the NSMenuValidation informal protocol. By default, NSMenu objects autoenable their menu items.

hippietrail commented 10 months ago

I found that in the application menu (Quit etc) I had to set item.target to NSApplication.shared or it would be ghosted. But for the other menus I had to set item.target to either self or not set it to anything. But if I set it to NSApplication.shared then it would be ghosted!