UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on 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 :)

4      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.