简体   繁体   中英

Create a Window on a status bar app for macOS

Warning: macOS dev beginner here.

I have a menu bar app (with no dock). Most of the app's functionality is in the menu (and implementation is in AppDelegate), but I need a separate window that will open once I click one of the menu items.

I want to use SwiftUI, Swift 5, Xcode 11.3.

I haven't found an appropriate way to do this. Which files and similar need to be created? How to open this window programatically?

@objc func openPreferences() {
  // open a new window here...
}

You have to create a window programatically. I have attached sample code of one of my apps:

private var windowController: NSWindowController?

fileprivate func createWindow()
{
    let storyboard = NSStoryboard(name: "Main", bundle: nil)

    self.windowController = storyboard.instantiateInitialController() as? NSWindowController

    // This is example code to show how to customize the hosted view controller. You can pass additional arguments here (may an important global variables that is declared in the AppDelegate).
    if let contentController = windowController?.contentViewController as? MyWindowViewController
    {
        // Do some assignments here
        // contentController.variable = ....
        // self.windowViewController = contentController // Maybe save for later use.
    }
}

@objc fileprivate func open()
{
    if self.windowViewController == nil
    {
        self.createWindow()
    }

    self.windowController?.showWindow(self)

    NSApp.activate(ignoringOtherApps: true) // Bring window to front.
}

I have linked the open() function to a button call (hence the @objc keyword). I think that you already did this, so my open() function would be your openPreferences function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM