Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SwiftUI macOS detect closing of window

Aim:

  • I have a swiftUI app that uses Window scene
  • When the user closes the red window, I would like call f1()

My attempt:

onDisappear doesn’t seem to be called when user closes the macOS app window

Question:

  1. In macOS (SwiftUI) how do I detect a window is closed by the user?
  2. Am I missing something?

Code

App

@main
struct DemoApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        
        Window("test", id: "test") {
            Color.red
                .onDisappear {
                    print("onDisappear")
                    f1()
                }
        }
    }
    
    func f1() {
        print("f1 called")
    }
}

ContentView

struct ContentView: View {
    @Environment(\.openWindow) private var openWindow
    var body: some View {
        Button("show red") {
            openWindow(id: "test")
        }
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use the NSWindow.willCloseNotification notification:

struct ContentView: View {
    
    var body: some View {
        
        Text("xyz")
            .onReceive(NotificationCenter.default.publisher(for: NSWindow.willCloseNotification)) { newValue in
                print("close")
            }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading