【发布时间】:2023-03-21 09:08:01
【问题描述】:
我想要一个按钮来打开一个新窗口并在 SwiftUI for MacOS 中加载一个视图(用于应用程序的首选项),但我不确定正确的方法。
我尝试创建一个函数并从有效的按钮操作中调用它,但在关闭新窗口时应用程序崩溃:
线程 1:EXC_BAD_ACCESS(代码=1,地址=0x20)
这是我的功能:
func openPreferencesWindow() {
var preferencesWindow: NSWindow!
let preferencesView = PreferencesView()
// Create the preferences window and set content
preferencesWindow = NSWindow(
contentRect: NSRect(x: 20, y: 20, width: 480, height: 300),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered,
defer: false)
preferencesWindow.center()
preferencesWindow.setFrameAutosaveName("Preferences")
preferencesWindow.contentView = NSHostingView(rootView: preferencesView)
preferencesWindow.makeKeyAndOrderFront(nil)
}
这是我的按钮调用它:
Button(action: {
openPreferencesWindow()
}) {
Text("Preferences").font(.largeTitle).foregroundColor(.primary)
}
我觉得应该在 AppDelegate 中构建窗口,但我不确定如何调用它。
【问题讨论】:
标签: macos button swiftui window nswindow