I'm looking for a simple (and Mac-specific) example of creating a window from the AppDelegate. My program has a login page that may or may not need to be displayed on app startup depending on whether the user is already logged in.
So far my AppDelegate's applicationDidFinishLaunching looks like this:
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
let main = NSStoryboard(name : "Main", bundle: nil).instantiateController(withIdentifier: "MainWindow") as! NSWindowController
main.window?.becomeFirstResponder()
let mainVc = NSStoryboard(name:"Main", bundle: nil).instantiateController(withIdentifier: "MainViewController") as! ViewController
main.window?.contentViewController = mainVc
}
But when I run the application nothing happens. I should note that I've unset the 'Main interface' property of the app settings. If I do not unset it, then two versions of the Window I want appear, which suggests that I'm almost correct with the above.
What am I missing?
You need to declare your NSWindowController variable main out of applicationDidFinishLaunching method. You need also to call makeKeyAndOrderFront(nil) instead of becomeFirstResponder:
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var main: NSWindowController!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
main = NSStoryboard(name : "Main", bundle: nil).instantiateController(withIdentifier: "MainWindow") as! NSWindowController
let mainVc = NSStoryboard(name:"Main", bundle: nil).instantiateController(withIdentifier: "MainViewController") as! ViewController
main.window?.contentViewController = mainVc
main.window?.makeKeyAndOrderFront(nil)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With