首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MacOS SwiftUI,如何防止窗口关闭操作

MacOS SwiftUI,如何防止窗口关闭操作
EN

Stack Overflow用户
提问于 2020-04-19 18:12:48
回答 1查看 617关注 0票数 0

因此,我有一个swiftUI应用程序,在某个时刻,我创建了一个NSWindow并分配了contentView,如下所示:

代码语言:javascript
运行
复制
        // ////////////////////////////////////////////////////////
        // 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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-19 19:21:30

我让它工作,不需要设置contentViewController,你可以使用标准的contentView:

代码语言:javascript
运行
复制
configurationWindow.contentView = NSHostingView(rootView: configurationView)

并禁止窗口在关闭时释放:

代码语言:javascript
运行
复制
configurationWindow.isReleasedWhenClosed = false

我仍然有兴趣知道窗口何时关闭,以便在之后执行某个操作,但这仍然解决了我的问题

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61302677

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档