Skip to content

Instantly share code, notes, and snippets.

@lucasfeijo
Created November 12, 2022 18:16
Show Gist options
  • Save lucasfeijo/7387300c908ad02a4b9a232fe983db49 to your computer and use it in GitHub Desktop.
Save lucasfeijo/7387300c908ad02a4b9a232fe983db49 to your computer and use it in GitHub Desktop.
SwiftUI macOS observe app focus
struct Example: View {
@State private var isWindowActive: Bool = false
var body: some View {
Text("Is Window Active? \(isWindowActive ? "yes" : "no")")
.modifier(WindowStateModifier(isWindowActive: $isWindowActive))
}
}
struct WindowStateModifier: ViewModifier {
var isWindowActive: Binding<Bool>
func body(content: Content) -> some View {
content
.onAppear {
self.isWindowActive.wrappedValue = true
}
#if os(macOS)
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification), perform: { _ in // swiftlint:disable:this
self.isWindowActive.wrappedValue = true
})
.onReceive(NotificationCenter.default.publisher(for: NSApplication.willResignActiveNotification), perform: { _ in // swiftlint:disable:this
self.isWindowActive.wrappedValue = false
})
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment