I am looking for a solution to create a macos windowless menu bar application with SwiftUI.
I have implement the function ralated to the menu bar, the problem is removing the main window and remove the application from the dock.
I have tried to set Application is agent (UIElement) to YES in Info.plist but it only hide the application from the dock while the window is still there.
And I have tried to modify @main but it doesn't work too.
Is there any way to achieve that? Thank you so much!
My code:
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()
}
}
