我想要一个按钮来打开新窗口并在Mac OS的SwiftUI中加载视图(用于应用程序的“首选项”),但是不确定这样做的正确方法。
我尝试创建一个函数并从可以执行的按钮操作中调用它,但是在关闭新窗口时,应用崩溃了:
线程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中构造,但不确定如何调用它。
您需要保留对创建的首选项窗口(如主窗口)的引用。
这是可能的解决方案(已通过Xcode 11.4 / macOS 10.15.5测试)
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
var window: NSWindow!
var preferencesWindow: NSWindow! // << here
@objc func openPreferencesWindow() {
if nil == preferencesWindow { // create once !!
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.isReleasedWhenClosed = false
preferencesWindow.contentView = NSHostingView(rootView: preferencesView)
}
preferencesWindow.makeKeyAndOrderFront(nil)
}
// ... other code
现在按钮看起来像
Button(action: {
NSApp.sendAction(#selector(AppDelegate.openPreferencesWindow), to: nil, from:nil)
}) {
Text("Preferences").font(.largeTitle).foregroundColor(.primary)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句