我正在寻找一种使用SwiftUI创建macOS无窗口菜单栏应用的解决方案。
我已经实现了与菜单栏相关的功能,问题在于如何去除主窗口并将应用从dock中移除。
我尝试在Info.plist中将"Application is agent (UIElement)"设置为"YES",但它只隐藏了应用程序,而窗口仍然存在。
我也尝试修改@main,但它也不起作用。
有没有办法实现这个?非常感谢!
我的代码:
- App.swift
我已经实现了与菜单栏相关的功能,问题在于如何去除主窗口并将应用从dock中移除。
我尝试在Info.plist中将"Application is agent (UIElement)"设置为"YES",但它只隐藏了应用程序,而窗口仍然存在。
我也尝试修改@main,但它也不起作用。
有没有办法实现这个?非常感谢!
我的代码:
- App.swift
import SwiftUI
@main
struct DiskHealthApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
class AppDelegate: NSObject, NSApplicationDelegate {
var statusItem: NSStatusItem?
var popOver = NSPopover()
func applicationDidFinishLaunching(_ notification: Notification) {
let menuView = ContentView()
popOver.behavior = .transient
popOver.animates = true
popOver.contentViewController = NSViewController()
popOver.contentViewController?.view = NSHostingView(rootView: menuView)
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
if let menuButton = statusItem?.button {
menuButton.image = NSImage(systemSymbolName: "externaldrive", accessibilityDescription: nil)
menuButton.action = #selector(menuButtonToggle)
}
}
@objc func menuButtonToggle() {
if let menuButton = statusItem?.button {
self.popOver.show(relativeTo: menuButton.bounds, of: menuButton, preferredEdge: NSRectEdge.minY)
}
}
}
ContentView.swift
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Hello, world!")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Main.storyboard
:( - IvanEFanEmptyView().frame(width:.zero)
来替代AnyView
,因为AnyView
可能不再有没有参数的初始化程序。 - gtxtreme