簡體   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