-[NSWindowController loadWindow] 中的编程 window 创建无效

Programmatic window creation in -[NSWindowController loadWindow] not working

我正在尝试以编程方式创建 NSWindowController 及其关联的 window。为此,我覆盖了 window 控制器的 loadWindow 并在我的应用委托中创建了 window 控制器:

class MainWindowController: NSWindowController {
    override func loadWindow() {
        print("loadWindow")
        self.window = NSWindow(contentRect: NSMakeRect(100, 100, 100, 100), styleMask: [.titled, .resizable, .miniaturizable, .closable], backing: .buffered, defer: false)
    }
}

@main
class AppDelegate: NSObject, NSApplicationDelegate {
    var mwc: MainWindowController!

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        self.mwc = MainWindowController(window: nil)
        self.mwc.showWindow(nil)
    }
}

当我 运行 这样做时,我没有看到 window,“loadWindow”也没有打印到控制台,所以它甚至没有被调用。有什么想法吗?

正如@Willeke 指出的那样,loadWindow 只会为 nib 调用

但由于您正在调用 showWindow,因此您可以覆盖它

import Cocoa

class MainWindowController: NSWindowController {
    override func loadWindow() {
        print("loadWindow")
    }

    override func showWindow(_ sender: Any?) {
        print("showWindow")
        self.window = NSWindow(contentRect: NSMakeRect(100, 100, 100, 100), styleMask: [.titled, .resizable, .miniaturizable, .closable], backing: .buffered, defer: false)
        window?.makeKeyAndOrderFront(sender)
    }
}

@main
class AppDelegate: NSObject, NSApplicationDelegate {
    var mwc: MainWindowController!

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        self.mwc = MainWindowController(window: nil)
        self.mwc.showWindow(nil)
    }

    static func main() {
        let app = NSApplication.shared
        let delegate = AppDelegate()
        app.delegate = delegate
        app.setActivationPolicy(.regular)
        app.activate(ignoringOtherApps: true)
        app.run()
    }
}