Created
November 12, 2022 18:16
-
-
Save lucasfeijo/7387300c908ad02a4b9a232fe983db49 to your computer and use it in GitHub Desktop.
SwiftUI macOS observe app focus
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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