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:
- In macOS (SwiftUI) how do I detect a window is closed by the user?
- 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 :
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")
}
}
}