swift - Swift+Macos 失去焦点时自动关闭弹出窗口
问题描述
我正在编写一个小应用程序,它在菜单栏中显示一个带有弹出视图的图标。
我以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
,但只有当应用程序失去焦点时才会触发,所以如果我直接单击菜单栏项并单击屏幕上的其他位置,我没有收到该事件。我引用的示例应用程序似乎没有连接这些事件,但仍按预期工作。
我刚刚开始 swift ui 编程,所以无法弄清楚我在这里缺少什么。
解决方案
不确定您是否仍在寻找解决方案,但我刚刚遇到了同样的问题,我发现这个例子似乎可以完成这项工作。希望这可以帮助。
推荐阅读
- javascript - Nuxt 现在部署失败:错误 nuxt@1.0.0:“节点”不兼容
- mysql - 存储过程输出返回 Null
- ios - 如何在 iOS 13 上设置 UIToolbar 高度
- python - 电池是否实时插入(在 Linux 上),需要在代码中快速修复
- r - 使用数据框从嵌套列表中绘制 ggplot
- python - 获取两个日期时间对象之间的时间差,如小时、分钟和秒
- c# - 事件实例字段成员可以为空吗(假设它没有被强制设置为空)?
- python - 如何在odeint中使用已知值?
- python - 使用 Kitti 图像从 ResNet101 主干中获取 Nan 结果
- java - Boolean Expression for two conditions of an element of a list