繁体   English   中英

Cocoa Mac:从AppDelegate创建窗口

[英]Cocoa Mac : creating window from AppDelegate

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

到目前为止,我的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
}

但是当我运行应用程序时没有任何反应。 我应该注意,我已取消设置应用设置的“主界面”属性。 如果我没有取消它,那么我想要的两个版本的Window出现了,这表明我对上面几乎是正确的。

我错过了什么?

您需要在applicationDidFinishLaunching方法中声明您的NSWindowController变量main。 您还需要调用makeKeyAndOrderFront(nil)而不是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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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