【问题标题】:Opening a closed NSWindow in Swift crashes application在 Swift 中打开一个关闭的 NSWindow 会导致应用程序崩溃
【发布时间】:2019-11-14 15:35:00
【问题描述】:

我在 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, 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()
    }
}

【问题讨论】:

    标签: swift macos swiftui nswindow


    【解决方案1】:

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

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

    见上面的最后一行。

    【讨论】:

      猜你喜欢
      • 2019-11-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多