f1()
onDisappear
doesn't seem to be called when user closes the macOS app window
@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")
}
}
struct ContentView: View {
@Environment(\.openWindow) private var openWindow
var body: some View {
Button("show red") {
openWindow(id: "test")
}
}
}
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
}
}
}
}