[英]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.我以https://github.com/twostraws/SwiftOnSundays/tree/master/013%20TextTransformer为例。
One difference I am seeing in my test app is the popover view controller is not getting dismissed when view loses focus.我在我的测试应用程序中看到的一个区别是,当视图失去焦点时,popover 视图控制器不会被解除。
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.我尝试添加applicationDidResignActive
但这仅在应用程序失去焦点时触发,因此如果我直接单击菜单栏项并单击屏幕上的其他位置我没有收到该事件。 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.我刚刚开始快速 ui 编程,所以无法弄清楚我在这里缺少什么。
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.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.