macosswiftui

How to detect closing of window?


Aim:

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

  • For a "SwiftUI way" to do this, check out the environment property controlActiveState. This value will be set to .inactive when the window loses focus, and when the window is closed.

    struct ContentView: View {
        @Environment(\.controlActiveState) private var controlActiveState
    
        var body: some View {
            Text("Hello, World!")
                .onChange(of: controlActiveState) { newValue in
                    switch newValue {
                    case .key, .active:
                        break
                    case .inactive:
                        // Do your stuff.
                    @unknown default:
                        break
                    }
                }
        }
    }