我已经以传统方式打开了窗口,但是我想通过单击关闭框(红色按钮)在关闭窗口时运行一些代码。有这样做的好方法吗?
func openMyWindow()
{
myWindow = (NSWindow(
contentRect: NSRect(x: 100, y: 100, width: 100, height: 600),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered, defer: false))
myWindow!.contentView = NSHostingView(rootView: MyWindowView())
myWindow!.makeKeyAndOrderFront(nil)
}
很好的问题..不久前我也为此感到挣扎。
您可以使AppDelegate或类符合NSWindowDelegate
协议。
然后将窗口的委托传递给self
myWindow.delegate = self
并实现以下功能通过关闭动作通知
func windowShouldClose(_ sender: NSWindow) -> Bool
{}
编辑:
使用SwiftUI生命周期时,可以添加AppDelegate。您也可以实现自己的WindowManager类。这是一个例子:
class WindowManager : NSObject, NSWindowDelegate {
var popUpWindow : NSWindow? = nil
override init() {}
func openMyWindow()
{
popUpWindow = (NSWindow(
contentRect: NSRect(x: 100, y: 100, width: 100, height: 600),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered, defer: false))
popUpWindow!.contentView = NSHostingView(rootView: PopUpView())
popUpWindow!.makeKeyAndOrderFront(nil)
popUpWindow?.delegate = self
}
func windowShouldClose(_ sender: NSWindow) -> Bool
{
print("Window will close")
return true
}
}
struct PopUpView : View {
var body: some View {
Text("This is a new popup view")
}
}
在您的类中创建并保存该类,struct _: App
然后通过此Manager打开Windows。
@main
struct macSwiftUICycleApp: App {
let persistenceController = PersistenceController.shared
let windowManager : WindowManager = WindowManager() //<< Here keep the instance of your WindowManager
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
.onAppear {
windowManager.openMyWindow() //<< Just a test to open another window on startup
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句