yyasutake
yyasutake

Reputation: 1

Trying to show a pop-up context menu on an NSButton within an NSMenuItem in Cocoa

I am trying to show a context menu in a macOS menu bar application when I right-click an NSButton within an NSMenuItem. The context menu appears as expected when the NSButton is placed directly on an NSView, but it does not work when I embed it in an NSMenu. Does anyone know how to make this work?

I have created a custom subclass of NSButton so that it shows a context menu on right-click.

class RightClickableButton: NSButton {
    
    override func rightMouseDown(with event: NSEvent) {
        let menu: NSMenu = NSMenu()
        menu.addItem(NSMenuItem(title: "Item", action: #selector(itemAction), keyEquivalent: ""))
        NSMenu.popUpContextMenu(menu, with: event, for: self)
    }
   
    @objc func itemAction() {}
    
}

A right-clickable button will be added to an NSView (in the future, I want to add multiple buttons to this NSView), and the view will be set in an NSMenuItem.

@main
class AppDelegate: NSObject, NSApplicationDelegate {
    
    let statusItem: NSStatusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength);
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        
        let menu: NSMenu = NSMenu()
        let buttonsMenuItem: NSMenuItem = NSMenuItem()
        let buttonsView: NSView = NSView(frame: NSRect(x: 0, y: 0, width: 200, height: 30))
        let button: RightClickableButton = RightClickableButton(title: "Button", target: self, action: #selector(buttonAction))
        button.frame = NSRect(x: 0, y: 0, width: 100, height: 30)
        buttonsView.addSubview(button)
        buttonsMenuItem.view = buttonsView
        menu.addItem(buttonsMenuItem)
        statusItem.menu = menu
        statusItem.button?.title = "MenuApp"
        
    }
    
    @objc func buttonAction() {}
}

The following is the image I want to achieve exactly (I am currently developing a window switcher app). After listing the windows of running applications, the user can choose to add some of them to the top of the menu. If one of them is clicked, it navigates to that application’s window. If the user wants to remove an added item, they can right-click it, and a pop-up menu to remove the item will be shown. Visualization of what I want to achieve

Upvotes: 0

Views: 89

Answers (0)

Related Questions