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

rre*_*hel 6 macos menubar swiftui

我正在使用 SwiftUI 的新 API 构建 macOS 菜单栏应用程序MenuBarExtra,但遇到了一些奇怪的问题。

我已经实现了一个设置窗口,可以通过以下调用打开该窗口:

if #available(macOS 13, *) {
    NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil)
} else {
    NSApp.sendAction(Selector(("showPreferencesWindow:")), to: nil, from: nil)
}
Run Code Online (Sandbox Code Playgroud)

我还将该Application is agent标志设置为YESin info 我的项目属性。

不幸的是,每当我通过菜单栏打开设置窗口时,它都会在后台打开并且根本不可见。我真的不知道如何从这里继续。我考虑过以下几点:

  • 以编程方式改变焦点(似乎不存在)
  • 打开一个单独的窗口(由于代理设置,这似乎不起作用)

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

Dan*_*iel 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
Run Code Online (Sandbox Code Playgroud)

最后一个窗口关闭后,再次使该应用程序成为代理/附件应用程序:

 NSApp.hide(self)
 NSApp.setActivationPolicy(.accessory)
Run Code Online (Sandbox Code Playgroud)

您可能想使用此扩展:

extension NSApplication {

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

    static func hide() {
        NSApp.hide(self)
        NSApp.setActivationPolicy(.accessory)
}
Run Code Online (Sandbox Code Playgroud)