0

所以我有一个 swiftUI 应用程序,有时我会创建一个 NSWindow 并分配 contentView,如下所示:

        // ////////////////////////////////////////////////////////
        // Add token window
        // ////////////////////////////////////////////////////////

        let configurationView = ConfigurationView().environmentObject(store)

        configurationWindow = NSWindow(
            contentRect: NSRect(x:0, y: 0, width: 480, height: 500),
            styleMask: [.titled, .closable, .miniaturizable, .fullSizeContentView],
            backing: .buffered, defer: false
        )
        configurationWindow.center()
        configurationWindow.setFrameAutosaveName("BSchauer")
        let hostingController = NSHostingController(rootView: configurationView)
        configurationWindow.contentViewController = hostingController
        configurationWindow.makeKeyAndOrderFront(nil)
        configurationWindow.setIsVisible(false)
    ... 
   // later on in the code
   @objc func toggleConfigurationWindow() {
        if self.configurationWindow.isVisible {
            self.configurationWindow.setIsVisible(false)
            if let button = self.statusBarItem.button {
                self.popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
            }
        } else {
            self.configurationWindow.setIsVisible(true)

            self.configurationWindow.contentViewController?.view.window?.becomeKey()
        }
    }

您会看到我与窗口交互以将其呈现给用户的方式是通过可见标志,现在问题是当窗口通过顶部栏上的关闭按钮显示和关闭时,窗口以某种方式被卸载(?)下次用户尝试与应用程序交互并重新打开窗口时,我会遇到分段错误。

我尝试的一件事是不要将可见性设置为 false,而是再次重新创建窗口,但我仍然遇到分段错误。

我找到的所有以前的答案都是处理处理 NSViewController 并覆盖该方法的旧windowShouldClose方法,但我似乎无法让它工作。

TL:DR:当用户按下窗口上的红色关闭按钮时,我只想将其可见性设置为 false,而不是窗口被破坏

4

1 回答 1

2

我做到了,不需要设置contentViewController,你可以使用标准的contentView:

configurationWindow.contentView = NSHostingView(rootView: configurationView)

并禁用关闭时释放的窗口:

configurationWindow.isReleasedWhenClosed = false

我仍然有兴趣知道窗口何时关闭,之后可能会执行操作,但这仍然解决了我的问题

于 2020-04-19T11:21:29.547 回答