Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa Mac : creating window from AppDelegate

Tags:

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?

like image 816
SuddenMoustache Avatar asked Oct 05 '16 14:10

SuddenMoustache


1 Answers

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
    }
}
like image 178
Leo Dabus Avatar answered Sep 25 '22 16:09

Leo Dabus