SwiftUI:窗口关闭时运行代码 macOS

iph*_*aaw 6 macos window swiftui

我已经以传统方式打开了窗口,但我想在通过单击关闭框(红色按钮)关闭窗口时运行一些代码。有没有好的方法可以做到这一点?

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)
}
Run Code Online (Sandbox Code Playgroud)

dav*_*dev 6

很好的问题..我不久前也在这个问题上挣扎过。

您可以使您的AppDelegate或类符合NSWindowDelegate协议。

然后self作为窗口的委托传递

myWindow.delegate = self
Run Code Online (Sandbox Code Playgroud)

并实现以下功能以通过关闭操作来通知

func windowShouldClose(_ sender: NSWindow) -> Bool
{}
Run Code Online (Sandbox Code Playgroud)

编辑:

当您使用 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")
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的中创建并保存该类struct _: App,然后通过此管理器打开 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
                }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)