2

guys. I'm coding a Swift-based menu bar Mac app. Since the method NSStatusItem.popUpMenu()has been deprecated, there's problem dealing with the situation where I want to left-click to show some view while right-click for display the menu containing Preference and Quit.

I'm trying to set NSStatusItem.menu. But when it's not nil, it will always pop up the menu, so I cannot write a condition to judge left/right click. Helpless ...

Code here:

func applicationDidFinishLaunching(_ aNotification: Notification) {
    // Create the popover
    let popover = NSPopover()
    popover.contentSize = NSSize(width: 60, height: 60)
    popover.behavior = .transient
    popover.animates = false
    popover.contentViewController = NSHostingController(rootView: ContentView()) // SwiftUI view
    self.popover = popover

    // Create the status item
    self.statusItem = NSStatusBar.system.statusItem(withLength: CGFloat(NSStatusItem.variableLength))

    // Create the menu
    let menu = NSMenu()
    menu.addItem(withTitle: "Preferences...", action: nil, keyEquivalent: ",")
    menu.addItem(NSMenuItem.separator())
    menu.addItem(withTitle: "Quit", action: #selector(quitApp(_:)), keyEquivalent: "q")
    self.menu = menu

    if let button = self.statusItem.button {
        button.image = NSImage(named: "StatusIcon")
        button.action = #selector(chooseAction(_:))
        button.sendAction(on: [.leftMouseUp, .rightMouseUp])
    }
}

@objc func chooseAction(_ sender: AnyObject?) {
    let event = NSApp.currentEvent!

    if event.type == NSEvent.EventType.leftMouseUp {
        print("left")
    } else {
        print("Right")
    }
}

Thanks for your help.

Toto
  • 570
  • 4
  • 13

0 Answers0