所以我有一个 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,而不是窗口被破坏