在 Swift 中打开关闭的 NSWindow 会使应用程序崩溃

Opening a closed NSWindow in Swift crashes application

我在 SwiftUI Mac 应用程序中有一个首选项 window。 window 通过单击 "Preferences..." 菜单项打开。 window 会在第一次打开时出现。但是如果首选项 window 关闭然后从菜单项重新打开,应用程序将崩溃。如何正确关闭并重新打开首选项 window 而不会导致应用程序崩溃?

AppDelegate.swift

import Cocoa
import SwiftUI

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    var window: NSWindow!
    var prefsWindow: NSWindow!

    @IBAction func openPrefsWindow(_ sender: NSMenuItem) {

        let prefsView = PreferencesView(

        prefsWindow = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
            styleMask: [.titled, .closable],
            backing: .buffered,
            defer: false)
        prefsWindow.center()
        prefsWindow.title = "Preferences"
        prefsWindow.setFrameAutosaveName("Preferences Window")
        prefsWindow.contentView = NSHostingView(rootView: prefsView)
        prefsWindow.makeKeyAndOrderFront(nil)
    }

    func applicationDidFinishLaunching(_ aNotification: Notification) {

        let contentView = ContentView()

        window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
            styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
            backing: .buffered,
            defer: false)
        window.center()
        window.setFrameAutosaveName("Main Window")
        window.contentView = NSHostingView(rootView: contentView)
        window.makeKeyAndOrderFront(nil)
    }
}

PreferencesView.swift

import SwiftUI

struct PreferencesView: View {
    var body: some View {
        Text("Preferences Window")
            .frame(width: 400, height: 200)
    }
}

struct PreferencesView_Previews: PreviewProvider {
    static var previews: some View {
        PreferencesView()
    }
}

与SwiftUI无关。您必须像这样为 prefesWindow 设置一些内容:

  .....
       prefsWindow.contentView = NSHostingView(rootView: prefsView)
       prefsWindow.makeKeyAndOrderFront(nil)
       prefsWindow.isReleasedWhenClosed = false

 }

见上面最后一行。