NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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

1      

Hacking with Swift is sponsored by MadMachine

SPONSORED Want to explore your Swift skill outside of the Apple world? Join the MadMachine community and start to program microcontrollers in Swift.

Get it 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.