Swift + Macos失去焦点时自动关闭弹出窗口

时间:2019-08-24 05:08:36

标签: swift macos storyboard

我正在编写一个小型应用程序,该应用程序会在菜单栏中显示带有弹出视图的图标。

我以https://github.com/twostraws/SwiftOnSundays/tree/master/013%20TextTransformer为例。

我在测试应用程序中看到的一个区别是,当视图失去焦点时,弹出视图控制器不会消失。

这是我的应用程序委托,

@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)
        }
    }
}

我尝试添加applicationDidResignActive,但这仅在应用程序失去焦点时才被触发,因此,如果我直接单击菜单栏项,然后单击屏幕上的其他位置,则不会得到该事件。我引用的sampleapp似乎并没有针对这些事件进行连接,但仍然可以按预期运行。

我刚刚开始进行快速的ui编程,所以无法弄清楚我在这里缺少什么。

1 个答案:

答案 0 :(得分:0)

不知道您是否仍在这里寻找解决方案,但是我遇到了同样的问题,发现this example似乎可以解决此问题。希望这会有所帮助。

相关问题