0

I have an NSStatusItem with a custom view (TimeView) set but this blocks the click from displaying the NSMenu associated with the NSStatusItem. If I disable the view for the NSStatusItem then the menu shows correctly, however, if I enable it then nothing happens when I click on the view.

class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var statusMenu: NSMenu!

    let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(NSVariableStatusItemLength)


    func applicationDidFinishLaunching(aNotification: NSNotification) {
        statusItem.view = TimeView(statusItem: statusItem)//Commenting out this line provides the correct functionality for displaying the menu
        statusItem.menu = statusMenu
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }    

}

Many thanks, Ben

BenJacob
  • 957
  • 10
  • 31

1 Answers1

0

So I found a way of accomplishing this. You can use NSStatusItem'spopUpStatusItemMenu(menu: NSMenu) method to show the menu in the views mouseDown(event: NSEvent) method.

However this does not take care of highlighting the NSStatusItem. The simplest way I could find to do that is to make the view conform to NSMenuDelegate and set it as the menu delegate. Then you can override the menuWillOpen(menu: NSMenu) and menuDidClose(menu: NSMenu) methods in the following manner:

func menuWillOpen(menu: NSMenu) {
    drawHighlight(true)
}

func menuDidClose(menu: NSMenu) {
    drawHighlight(false)
}

func drawHighlight(highlight:Bool) {
    let image = NSImage(size: self.frame.size)
    image.lockFocus()
    statusItem.drawStatusBarBackgroundInRect(self.bounds, withHighlight: highlight)
    image.unlockFocus()
    self.layer?.contents = image
}
BenJacob
  • 957
  • 10
  • 31