我希望不在 macOS 上显示 SwiftUI 应用程序的窗口。该应用程序使用 SwiftUI 的应用程序生命周期,并且仅在状态栏中运行。启动时显示窗口是不必要的。但我不确定如何绕过WindowGroup. 不存在“ ”这样的东西EmptyScene,将“ ”放入EmptyView“WindowGroup当然”会创建一个空窗口。
@main
struct MyApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
Run Code Online (Sandbox Code Playgroud)
我基本上只需要应用程序委托。我猜使用默认的 AppKit 生命周期更有意义,但如果有一种方法可以使用 SwiftUI 的生命周期,我很想知道。
小智 22
在您的 AppDelegate 中,在 applicationDidFinishLaunching 中执行以下操作:
func applicationDidFinishLaunching(_ notification: Notification) {
// Close main app window
if let window = NSApplication.shared.windows.first {
window.close()
}
// Code continues here...
}
Run Code Online (Sandbox Code Playgroud)
例如:
class AppDelegate: NSObject, NSApplicationDelegate {
var popover = NSPopover.init()
var statusBar: StatusBarController?
func applicationDidFinishLaunching(_ notification: Notification) {
// Close main app window
if let window = NSApplication.shared.windows.first {
window.close()
}
// Create the SwiftUI view that provides the contents
let contentView = ContentView()
// Set the SwiftUI's ContentView to the Popover's ContentViewController
popover.contentSize = NSSize(width: 160, height: 160)
popover.contentViewController = NSHostingController(rootView: contentView)
// Create the Status Bar Item with the above Popover
statusBar = StatusBarController.init(popover)
}
}
Run Code Online (Sandbox Code Playgroud)
l -*_*c l 10
\n\n该应用程序使用SwiftUI 的应用程序生命周期,并且仅在状态栏中运行。
\n
用一个MenuBarExtra\nscene 通过本机 SwiftUI 生命周期在系统菜单栏中呈现持久控件。(Xcode 14.2、macOS Ventura)
@main\nstruct MyStatubarMenuApp: App {\n var body: some Scene {\n // -- no WindowGroup required --\n // -- no AppDelegate needed --\n MenuBarExtra { \n Text("Hello Status Bar Menu!")\n MyCustomSubmenu()\n Divider()\n Button("Quit") { NSApp.terminate(nil) }\n } label: {\n Image(systemName: "bolt.fill")\n }\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n笔记:
\nApplication is agent = YES应用Info.plist程序图标,使其不显示在 Dock 上。systemName:System Settings\xe2\x80\xa6当>Appearance更改时,SF 符号将自动切换外观。@Environment(\\.colorScheme) 目前不在应用程序/场景级别更新如果您的应用程序有设置(谁没有?),您可以这样做:
@main
struct TheApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
Settings {
SettingsView()
}
}
}
Run Code Online (Sandbox Code Playgroud)
你应该能够做这样的事情:
var body: some Scene {
WindowGroup {
ZStack {
EmptyView()
}
.hidden()
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4959 次 |
| 最近记录: |