我正在寻找一个从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
}
但是当我运行应用程序时没有任何反应。我应该注意到,我已经取消了主界面的设置'应用设置的属性。如果我没有取消它,那么我想要的两个版本的窗口出现了,这表明我几乎正确使用上述。
我错过了什么?
答案 0 :(得分:2)
您需要在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
}
}