创建一个无窗口的SwiftUI macOS应用程序?

创建一个无窗口的SwiftUI macOS应用程序?,swift,macos,cocoa,swiftui,Swift,Macos,Cocoa,Swiftui,我正在使用SwiftUI为macOS创建一个菜单栏应用程序。我已经了解了如何创建菜单栏项,以及如何在Dock中隐藏图标。但还有一件事我需要弄清楚,有一个适当的菜单栏应用程序,那就是如何不显示屏幕上的窗口(见截图) 在对@main App类使用SwiftUI时,我似乎必须返回一个包含一些内容的WindowGroup。我尝试了EmptyView()等,但它必须是“符合场景的某个视图” 我所拥有的 这是我到目前为止的代码 import SwiftUI import Combine class Ap

我正在使用SwiftUI为macOS创建一个菜单栏应用程序。我已经了解了如何创建菜单栏项,以及如何在Dock中隐藏图标。但还有一件事我需要弄清楚,有一个适当的菜单栏应用程序,那就是如何不显示屏幕上的窗口(见截图)

在对
@main App
类使用SwiftUI时,我似乎必须返回一个包含一些内容的
WindowGroup
。我尝试了
EmptyView()
等,但它必须是“符合
场景的某个视图”

我所拥有的 这是我到目前为止的代码

import SwiftUI
import Combine

class AppViewModel: ObservableObject {
  @Published var showPopover = false
}

@main struct WeeksApp: App {
  @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
  @Environment(\.scenePhase) private var scenePhase
  
  var body: some Scene {
    WindowGroup { Text("I don't want to show this window. I'm not sure if it's a hack and if there is a better way. I wrote an app as an agent, with the possibility to show a window later in the process. However, at startup, the app should not show a window.

I made an application delegate with the following code:

class Appdelegate: NSObject, NSApplicationDelegate {
    
    @Environment(\.openURL) var openURL
    var statusItem: NSStatusItem!

    func applicationDidFinishLaunching(_ notification: Notification) {
        statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)

        statusItem.button!.image = NSImage(named: "AppIcon")
        statusItem.isVisible = true
        statusItem.menu = NSMenu()
        addConfigrationMenuItem()
        
        BundleLocator().checkExistingLaunchAgent()
        
        if let window = NSApplication.shared.windows.first {
            window.close()
        }
    }
}
导入快捷界面
进口联合收割机
类AppViewModel:ObserveObject{
@已发布的var showPopover=false
}
@主结构周应用程序:应用程序{
@NSApplicationedLegateAptor(AppDelegate.self)var AppDelegate
@环境(\.scenePhase)私有变量scenePhase
var body:一些场景{

WindowGroup{Text(“我不想显示此窗口。我不确定这是否是黑客行为,也不确定是否有更好的方法。我作为代理编写了一个应用程序,可以在稍后的过程中显示窗口。但是,在启动时,应用程序不应显示窗口

我用以下代码创建了一个应用程序委托:

@main
struct RestartAtDateTryoutApp: App {
    
    @NSApplicationDelegateAdaptor(Appdelegate.self) var appDelegate
    var scheduler = Scheduler()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .handlesExternalEvents(preferring: Set(arrayLiteral: "ContentView"), allowing: Set(arrayLiteral: "*"))
                .environmentObject(scheduler)
                .frame(width: 650, height: 450)
        }
        .handlesExternalEvents(matching: Set(arrayLiteral: "ContentView"))
    }
}
请注意,最后我关闭了窗口,该窗口仅允许我的应用程序以菜单栏应用程序的形式启动。但是,我确实有一个内容视图,可以稍后打开。因此,该应用程序如下所示:

这给了我一个菜单栏应用程序,其中一个是带有用户界面的窗口。 我希望这也适用于你的应用程序


谢谢,但正如我在帖子中所说,“我更喜欢SwiftUI解决方案。我知道它可以用“旧”的方式完成。”。我想用SwiftUI。什么?为什么这是一个矛盾修饰法?你必须用应用程序代表的“旧”方式来完成。