我想要一个按钮来打开一个新窗口并在 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)
}
Run Code Online (Sandbox Code Playgroud)
这是我调用它的按钮:
Button(action: {
openPreferencesWindow()
}) {
Text("Preferences").font(.largeTitle).foregroundColor(.primary)
}
Run Code Online (Sandbox Code Playgroud)
我觉得应该在 AppDelegate 中构建窗口,但我不确定我会如何调用它。
我正在为 SwiftUI 2.0 重新设计我的应用程序,但在复制我可以使用 AppDelegate 执行的操作时遇到了问题。
我正在使用 NSViewRepresentable 来访问 NSWindow,这样我就可以删除窗口的标题栏(我知道它不在指南中,但永远不会提交)。.titled从 中删除时styleMask,应用程序崩溃。
struct WindowAccessor: NSViewRepresentable {
@Binding var window: NSWindow?
func makeNSView(context: Context) -> NSView {
let view = NSView()
DispatchQueue.main.async {
self.window = view.window
self.window?.isOpaque = false
self.window?.titlebarAppearsTransparent = true
self.window?.backgroundColor = NSColor.clear
self.window?.styleMask = [.fullSizeContentView]
self.window?.isMovableByWindowBackground = true
self.window?.backingType = .buffered
}
return view
}
func updateNSView(_ nsView: NSView, context: Context) {}
}
@main
struct MyApp_App: App {
@State private var window: NSWindow?
var body: …Run Code Online (Sandbox Code Playgroud)