I want to programmatically populate an NSMenuToolbarItem's NSMenu.
let toolbarItem = NSMenuToolbarItem(itemIdentifier: ...)
toolbarItem.image = ...
toolbarItem.label = ...
toolbarItem.menu.delegate = self
In my class that conforms to NSMenuDelegate protocol. I implemented the menuNeedsUpdate(_:) method:
func menuNeedsUpdate(_ menu: NSMenu) {
menu.items.removeAll()
menu.items = makeMenuItems()
}
In my makeMenuItems() method:
func makeMenuItems() -> [NSMenuItem] {
[NSMenuItem(title: "Dogs", action: nil, keyEquivalent: ""),
NSMenuItem(title: "Cats", action: nil, keyEquivalent: ""),
NSMenuItem(title: "Foxes", action: nil, keyEquivalent: "")]
}
When I run the app and check to see if there are three NSMenuItem that I expected. This is what I got:
I found it strange that "Dogs" NSMenuItem is missing.
So what I did was insert a blank NSMenuItem to make the "Dogs" NSMenuItem appear. I refactored makeMenuItems() method like this:
func makeMenuItems() -> [NSMenuItem] {
[NSMenuItem(),
NSMenuItem(title: "Dogs", action: nil, keyEquivalent: ""),
NSMenuItem(title: "Cats", action: nil, keyEquivalent: ""),
NSMenuItem(title: "Foxes", action: nil, keyEquivalent: "")]
}
I run the app again and it is what I expected:
Is this a normal behaviour? If not, should I or somebody file a feedback to Apple? I can't find any documentation about the .init() initialiser. There are documentation for init(title:action:keyEquivalent:) and init(coder:) initialiser.
This was done on macOS Sonoma.

