NSStatusBar にあるアイコンをクリックした際に NSPopover を表示し、フォーカスが外れたら自動で閉じる

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    
    let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-2)
    let popover = NSPopover()

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
        
        if let button = statusItem.button {
            button.image = NSImage(named: "...")
            button.action = Selector("showPopover:")
            button.target = self
        }
        
        let vc = //  create ViewController
        popover.contentViewController = vc
        popover.behavior = .Transient
    }

    func showPopover(sender: AnyObject?) {
        if popover.shown {
            popover.performClose(sender)
        } else {
            if let button = statusItem.button {
                popover.showRelativeToRect(button.bounds, ofView: button, preferredEdge: NSMinYEdge)
                NSApplication.sharedApplication().activateIgnoringOtherApps(true)
            }
            
        }
    }
}

popover.behavior.Transient にすることでフォーカスが外れた場合に閉じられる。 さらに popover を表示する場合に NSApplication.sharedApplication().activateIgnoringOtherApps(true) とすることで、一番まえに持ってこれる。

こうしないと statusbar をクリックして popover は表示されるがフォーカスがそもそもされてないので、一度 viewcontroller の view をクリックしてからでないとフォーカスが外れない。結果 popover が閉じられないということが起きる。