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

我在SwiftUI Mac应用程序中有一个“偏好设置”窗口。通过单击“首选项...”菜单项打开该窗口。窗口在第一次打开时应显示。但是,如果关闭“首选项”窗口,然后从菜单项中重新打开它,则应用程序将崩溃。如何正确关闭并重新打开“首选项”窗口而不会导致应用程序崩溃?

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,.closable,.miniaturizable,.resizable,.fullSizeContentView],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()
    }
}
jrr1234567 回答:在Swift中打开一个关闭的NSWindow会使应用程序崩溃

它与SwiftUI无关。您必须像这样为prefesWindow设置一些东西:

SameSite=None;Secure

请参阅上面的最后一行。

本文链接:https://www.f2er.com/3101259.html

大家都在问