FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

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 :)

   

Hacking with Swift is sponsored by Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Get started

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.