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

MenuBar popover sometimes opens as a window

Forums > macOS

I have created a MacOS menubar app that when clicking on the menuitem, opens a popover. All is well, except that occasionally the popover will instead open up as an actual window. A lot of this code is what I've seen in different tutorials/examples of menubar apps.

I haven't been fully able to reliably reproduce, but I suspect that it has to do with some kind of race condition. In my content view, I fire off a request to load data from a URL. When that data has returned, I update the app state to display that data instead of a loading screen. Nothing particularly interesting in the ContentView.

        // popover created in AppDelegate.applicationDidFinishLaunching

        var popover = NSPopover.init()
        popover.behavior = .transient
        popover.contentSize = NSSize(width: 450, height: 300)
        popover.contentViewController = NSHostingController(rootView: contentView)

        // show/hide toggle of popover created like this
        @objc func togglePopover(_ sender: AnyObject) {
        if popover.isShown {
            hidePopover(sender)
        } else {
            showPopover(sender)
        }
    }

    func showPopover(_ sender: AnyObject) {
        if let statusBarButton = statusItem?.button {
            popover.show(relativeTo: statusBarButton.bounds, of: statusBarButton, preferredEdge: NSRectEdge.maxY)
        }
    }

    func hidePopover(_ sender: AnyObject) {
        popover.performClose(sender)
    }

There are no calls to create an NSWindow anywhere in my app, so I'm bit confused.

I am very new to Mac development and SwiftUI. Be gentle, thanks :)

4      

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!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.