MacOS SwiftUI 菜单栏应用程序的设置在后台打开

6
我正在使用SwiftUI的新MenuBarExtra API构建一个macOS菜单栏应用,并遇到了一些奇怪的问题。
我已经实现了一个可以通过以下调用打开的设置窗口:
if #available(macOS 13, *) {
    NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil)
} else {
    NSApp.sendAction(Selector(("showPreferencesWindow:")), to: nil, from: nil)
}

我还在我的项目属性中设置了Application is agent标志为YES

不幸的是,每当我通过MenuBar打开设置窗口时,它都会在后台打开,并且根本看不到。我真的不知道该怎么办。我考虑了以下几点:

  • 编程更改焦点(似乎不存在)
  • 打开一个单独的窗口(由于代理设置,这似乎无法工作)

有人遇到过这个问题并实施了解决方案吗?

1个回答

7

你可以通过编程方式更改激活策略。在打开首选项之前,运行以下代码:

NSApp.setActivationPolicy(.regular) //makes the app a "normal" app again with a menu bar and a visible dock icon
NSApp.activate(ignoringOtherApps: ignoringOtherApps) // Activates the app in order to bring the window to front. Otherwise your window may be hidden behind windows of other apps

在你的最后一个窗口关闭后,将该应用程序再次设置为代理/附件应用程序:

 NSApp.hide(self)
 NSApp.setActivationPolicy(.accessory)

您可能想使用这个扩展:

extension NSApplication {

    static func show(ignoringOtherApps: Bool = true) {
        NSApp.setActivationPolicy(.regular)
        NSApp.activate(ignoringOtherApps: ignoringOtherApps)
    }

    static func hide() {
        NSApp.hide(self)
        NSApp.setActivationPolicy(.accessory)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接