2016-10-05 84 views
3

我正在寻找一个从AppDelegate创建窗口的简单(和Mac特定的)示例。我的程序有可能会或可能不会需要上取决于用户是否已经登录应用程序启动时要显示的登录页面可可Mac:从AppDelegate创建窗口

到目前为止,我的AppDelegate的applicationDidFinishLaunching如下:

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 
} 

但是,当我运行应用程序没有任何反应。我应该注意到,我已经取消了应用设置的“主界面”属性。如果我没有解除它,那么两个版本的窗口我想出现,这表明我是差不多正确与上述。

我错过了什么?

+0

在进一步的检查,我AppDelegate.applicationDidFinishLaunching甚至不运行一旦我没有设置“主界面”选项... – SuddenMoustache

+0

你试试将'viewController'实例化为您自定义的'NSWindowController'类? – Astoria

回答

2

您需要声明您的NSWindowController变量主applicationDidFinishLaunching方法。你也需要调用makeKeyAndOrderFront(零),而不是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 
    } 
} 
相关问题