How to open NSWindow from function inside AppDelegate.swift?

Hi.
I have created status bar app. I have added global shortcut using HotKey by Sam Soffes. I want this shortcut to open window from Storyboard. My problem is that I don't know how to open NSWindow from function inside AppDelegate.swift. This project is written in UIKit and Swift using Xcode 12. Thank you in advance for help.

Accepted Reply

Can the problem be because NSWindow is in Storyboard?

Using storyboard may not be a problem if you know the right way to handle it.
I guess your NSWindow is embedded in an NSWindowController, no?

You can write some code to show an NSWindowController like this:
Code Block
let mainStoryboard = NSStoryboard(name: "Main", bundle: nil)
if let windowController = mainStoryboard.instantiateController(withIdentifier: "MyWindowController") as? NSWindowController {
windowController.showWindow(nil)
} else {
print("Cannot find MyWindowController")
}


I haven't tried this in a status bar app, but I think it should work.

Replies

I meant Cocoa instead of UIKit.
In AppDelegate, I declared

Code Block
    @IBOutlet weak fileprivate var splashWindow: NSWindow!

splashWindow is in the MainMenu.xib (I do not make it visible at launch)
I connect the 2.

Then in appDidFinishLaunching

Code Block
splashWindow.makeKeyAndOrderFront(splashWindow)
splashWindow.isWindowVisible = true

Thanks for the answer. Unfortunately, I can't connect NSWindow and AppDelegate.swift using Control or Connections Inspector. Can the problem be because NSWindow is in Storyboard?

Can the problem be because NSWindow is in Storyboard?

Using storyboard may not be a problem if you know the right way to handle it.
I guess your NSWindow is embedded in an NSWindowController, no?

You can write some code to show an NSWindowController like this:
Code Block
let mainStoryboard = NSStoryboard(name: "Main", bundle: nil)
if let windowController = mainStoryboard.instantiateController(withIdentifier: "MyWindowController") as? NSWindowController {
windowController.showWindow(nil)
} else {
print("Cannot find MyWindowController")
}


I haven't tried this in a status bar app, but I think it should work.
Did you declare AppDelegate as conforming to:

Code Block
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate { }


You also need to connect (in IB), the NSWindow to the AppDelegate object to set its delegate.
If it does not exist, insert an Object Controller (in IB) in MainMenu.xib.
Give it the AppDelegate class.