可可Mac:从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)而不是成为firstResponder:

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
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章