因此,我有一个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()
        }
    }您可以看到,我与窗口交互的方式是通过visible标志向用户显示它,现在的问题是,当窗口通过顶部栏上的close按钮显示并关闭时,窗口以某种方式被卸载(?)当用户下一次尝试与应用程序交互并重新打开窗口时,我得到了一个分段错误。
我尝试的其中一件事是,不是将可见性设置为false,而是重新创建窗口,但我仍然得到分割错误。
我之前找到的所有答案都是关于处理NSViewController和覆盖windowShouldClose方法的旧方法,但我似乎无法使其工作。
TL:DR:当用户按下窗口上的红色关闭按钮时,我只想将窗口的可见性设置为false
发布于 2020-04-19 19:21:30
我让它工作,不需要设置contentViewController,你可以使用标准的contentView:
configurationWindow.contentView = NSHostingView(rootView: configurationView)并禁止窗口在关闭时释放:
configurationWindow.isReleasedWhenClosed = false我仍然有兴趣知道窗口何时关闭,以便在之后执行某个操作,但这仍然解决了我的问题
https://stackoverflow.com/questions/61302677
复制相似问题