macOS:如何在不使用 Xib/Storyboard 的情况下创建和启动 NSViewController

macOS: How to create and launch a NSViewController without using Xib/Storyboard

我想在不使用故事板和 Xib 的情况下显示 NSViewController。我已经被转介了很多,无法找到工作。 WindowController 未显示。请参阅随附的代码和项目。

main.swift

import Cocoa

print("Hello, World!")

let delegate = AppDelegate()
NSApplication.shared.delegate = delegate
 
let ret = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)

AppDelegate.Swift

import Cocoa
 
class AppDelegate: NSObject, NSApplicationDelegate {
 
    func applicationDidFinishLaunching(_ aNotification: Notification) {
 
        WindowController().showWindow(self)
    }
 
 
}

WindowController.swift

import Cocoa

class WindowController: NSWindowController, NSWindowDelegate {
 
    init() {
        
        let window = Window()
 
        super.init(window: window)
        
        window.delegate = self
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Window.swift

import Cocoa

class Window: NSWindow {

    init() {
        
        let screen  = NSScreen.main!.frame
        let origin = NSPoint(x:screen.width/2, y: screen.height/2)
        
        super.init(contentRect: NSRect(origin: origin, size: NSSize(width: 600, height: 400)), styleMask: [.titled,.resizable,.miniaturizable,.closable], backing: .buffered, defer: false)
        
        self.contentViewController = ViewController()
    }
}

ViewController.swift

import Cocoa

class ViewController: NSViewController {
    
    override func loadView() {

        view = NSView()
    }
    
    init() {
          
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

         view.wantsLayer = true
         view.layer!.backgroundColor = NSColor.red.cgColor
    }
}

代码是运行,viewDidLoad正在调用。但是 window 是不可见的。这里是 attached project. 请帮助我找到解决方案。提前致谢!

更新 1.0:

我创建了 WindowController 作为强有力的参考。是的,保留 Window controller 而不是 deinit 是可行的。但是NSViewController还是没有显示。

class AppDelegate: NSObject, NSApplicationDelegate {
 
    let controller = WindowController()
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
 
        controller.showWindow(self)
    }
 
}

视图的大小为 (0, 0),window 已调整大小以适合视图。使用更大的视图:

override func loadView() {

    view = NSView(frame: NSMakeRect(0, 0, 500, 500))
}