TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Toggle a main window when tray icon clicked? How would you do that tried everything?

Forums > SwiftUI

spend many hours looking at a way not found one.

i use menubarextra but cannot figure out how i could toggle a main window when clicking the tray icon.

is this possible with menubar extra swiftui class? also digged the docs highly frustrated that this seems not possible yet still is a common pattern many osx apps implement.

i then digged githib and tried every recent swift ui project to see if it was implemented somewhere: nothing!

i basically want:

swiftui tray icon app with a main window initially hidden users clicks tray icon then main window appears centered under the tray icon. if it was shown it hides else its shown ( toggle on tray icon click) clicking right will open the tray menu with items like about and quit. any swiftui expert knows how i should implement this?

I literaly cannot find anything perhaps this is just not possible with seiftui menubar implementation?

Would very gratefull for a solution pulling my hairs out on this one

2      

I tried this

import AppKit
import SwiftUI

class AppDelegate: NSObject, NSApplicationDelegate, ObservableObject {

    private var statusItem: NSStatusItem!
    private var window: NSWindow!

    func applicationDidFinishLaunching(_ notification: Notification) {

        // Setup tray icon
        self.statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
        if let statusButton = self.statusItem.button {
            statusButton.image = NSImage(systemSymbolName: "chart.line.uptrend.xyaxis.circle", accessibilityDescription: "Chart Line")
            statusButton.action = #selector(toggleWindow)
        }

        // Create NSWindow
        self.window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 400, height: 400),
            styleMask: [.titled],  // Titled but no resize controls
            backing: .buffered, defer: false
        )

        self.window.standardWindowButton(.miniaturizeButton)?.isHidden = true
        self.window.standardWindowButton(.zoomButton)?.isHidden = true
        self.window.isReleasedWhenClosed = false
        self.window.contentView = NSHostingView(rootView: ContentView())
    }

    @objc
    func toggleWindow() {
        if let button = self.statusItem.button {
            if window.isVisible {
                self.window.orderOut(nil)
            } else {
                let buttonRect = button.window!.frame
                let windowRect = window.frame

                let xPos = buttonRect.origin.x + buttonRect.size.width/2.0 - windowRect.size.width/2.0
                let yPos = buttonRect.origin.y - windowRect.size.height

                window.setFrameOrigin(NSPoint(x: xPos, y: yPos))
                self.window.makeKeyAndOrderFront(nil)
                NSApp.activate(ignoringOtherApps: true)
            }
        }
    }
}

@main
struct MenuBarApp_SwiftUIApp: App {

    @NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate

    var body: some Scene {
        // This window group will not display any UI, so you can even leave it empty
        WindowGroup {}
    }
}

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .padding()
    }
}

But this returns something that look like:

Why is this so hard?! Why no good swift ui examples from apple... Argh frustration i have to spend 2 days on getting a this basic format for my app working

2      

Have you considered alternative user interface options, such as context menus or keyboard shortcuts, to complement the tray icon toggle functionality, and how might these enhance the overall usability?

2      

Have you considered alternative user interface options, such as context menus or keyboard shortcuts, to complement the tray icon toggle functionality, and how might these enhance the overall usability?

2      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.