Created
July 17, 2022 21:51
-
-
Save jordibruin/3000b4dc648bcb447ecf5d91a1e5f3ad to your computer and use it in GitHub Desktop.
simple menu bar swiftui
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
@main | |
struct MenuBarApp: App { | |
@NSApplicationDelegateAdaptor(StatusBarDelegate.self) var appDelegate | |
var body: some Scene { | |
WindowGroup { | |
ContentView() | |
} | |
.windowToolbarStyle(.automatic) | |
.windowStyle(.titleBar) | |
} | |
} | |
import SwiftUI | |
import Foundation | |
import AppKit | |
class StatusBarDelegate: NSObject, NSApplicationDelegate { | |
var popover: NSPopover! | |
var statusBarItem: NSStatusItem! | |
func applicationDidFinishLaunching(_ aNotification: Notification) { | |
// Create the SwiftUI view that provides the window contents. | |
let contentView = ContentView() | |
// Create the popover | |
let popover = NSPopover() | |
// popover.contentSize = NSSize(width: 250) | |
popover.behavior = .transient | |
popover.contentViewController = NSHostingController(rootView: contentView) | |
popover.becomeFirstResponder() | |
self.popover = popover | |
// Create the status item | |
self.statusBarItem = NSStatusBar.system.statusItem(withLength: CGFloat(NSStatusItem.variableLength)) | |
if let button = self.statusBarItem.button { | |
button.title = "🌟" | |
button.action = #selector(togglePopover(_:)) | |
} | |
} | |
@objc func togglePopover(_ sender: AnyObject?) { | |
if let button = self.statusBarItem.button { | |
if self.popover.isShown { | |
self.popover.performClose(sender) | |
} else { | |
self.popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY) | |
NSApplication.shared.activate(ignoringOtherApps: true) | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment