简体   繁体   中英

Swift+Macos Auto close popover window when focus is lost

I am writing a small app that display an icon in the menu bar with a popup view.

I followed https://github.com/twostraws/SwiftOnSundays/tree/master/013%20TextTransformer as an example.

One difference I am seeing in my test app is the popover view controller is not getting dismissed when view loses focus.

this is my app delegate,

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)

    let popupOver = NSPopover()

    @IBOutlet weak var menu: NSMenu!

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        statusItem.button?.title = "FT";
        statusItem.button?.target = self;
        statusItem.button?.action = #selector(showMenu)

        let storyBoard = NSStoryboard(name: "Main", bundle: nil)

        guard let viewController = storyBoard.instantiateController(withIdentifier: "FTViewController") as? ViewController else {
            fatalError("Unable to find 'FTViewController'")
        }

        popupOver.contentViewController = viewController
        popupOver.behavior = .semitransient
    }

    func applicationDidResignActive(_ notification: Notification) {
        popupOver.close()
    }

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

    @objc func showMenu() {

        if(popupOver.isShown) {
            popupOver.close()
        }
        else {
            guard let statusButton = statusItem.button else {
                fatalError("Unable to find status button")
            }

            popupOver.show(relativeTo: statusButton.bounds, of: statusButton, preferredEdge: .maxY)
        }
    }
}

I tried adding applicationDidResignActive but that's getting triggered only when the application loses focus so if i directly click the menu bar item and click else where on screen I am not getting that event. The sampleapp i referenced doesnt seem to hookup for these events but still works as expected.

I am just starting swift ui programming so couldnt figure out what I am missing here.

Not sure if you're still looking for a solution here, but I've just got stuck with the same problem and I found this example which seems to do the job. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM