-1

I can get the name of a NSMenuItem at the top level of the NSMenu of a NSPopUpButton.

I do this by adding an action to the NSPopUpButton:

@IBAction func menuDropdownAction(_ sender: Any) {

    let titleOfSelectedItem = (sender as AnyObject).titleOfSelectedItem

    print (titleOfSelectedItem! as Any)
}

But if I add a submenu to the NSMenu it just returns nil.

It seems to me that .titleOfSelectedItem applied to the NSPopUpButton should work for items buried in its submenus, but it seems not!

Any assistance would be gratefully accepted, there is a similar question, but its over 10 years old for cocoa and was no use to me. link

Willeke
  • 14,578
  • 4
  • 19
  • 47
moonmonkey
  • 125
  • 9
  • "was no use to me" Why not? Just get the submenu items. – Leo Dabus Mar 26 '22 at 00:35
  • Hi Leo, I tried " let selectedItemSubmenu = (sender as AnyObject).submenu" but this returns nil. any idea? – moonmonkey Mar 26 '22 at 01:07
  • 1
    try casting `as NSMenuItem`. Make sure that the sender is a menu item and that it is the one that contains a submenu. – Leo Dabus Mar 26 '22 at 01:13
  • 1
    `titleOfSelectedItem` is a method of `NSPopUpButton`. Is this the action method of a `NSPopUpButton`? What are you trying to accomplish? – Willeke Mar 26 '22 at 09:52
  • Hi Willeke, I have a NSPopUpButton and I want to return the titleOfSelectedItem, the code in the question works fine for items at the top level, but items in sub menus don't return anything. – moonmonkey Mar 27 '22 at 06:52
  • 1
    Does this answer your question? [Display selected sub-menuItem in NSPopUpButton](https://stackoverflow.com/questions/21779015/display-selected-sub-menuitem-in-nspopupbutton) – Willeke Mar 27 '22 at 08:58
  • 1
    Is the pop-up button in [Drop Down](https://developer.apple.com/design/human-interface-guidelines/macos/buttons/pull-down-buttons/) mode? – Willeke Mar 28 '22 at 06:54
  • There are two types I can define, pull down, and pop up. Its currently set to pop up. Thanks. – moonmonkey Mar 28 '22 at 22:13

1 Answers1

0

Swift is a strong typed language and you don't care about the type by writing Any and AnyObject.

Replace the sender with the real type

@IBAction func menuDropdownAction(_ sender: NSPopUpButton) {

then you can access all properties of the popup button

    let titleOfSelectedItem = sender.titleOfSelectedItem
    let menu = sender.menu!
    let firstMenuItem = menu.item(at: 0)!
    let subMenu = firstMenuItem.submenu!
vadian
  • 274,689
  • 30
  • 353
  • 361