Detect focused window on macOS
To detect the activated window on macOS we can read controlActiveState environment value.
The value is set to .key
when the window is key window and to .inactive
when the window loses focus and we activate another window.
struct ContentView: View {
@Environment(\.controlActiveState) var controlActiveState
var body: some View {
Text("Hello, world!")
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(
// customize appearance of view in key window
controlActiveState == .key ? Color.gray : Color.black
)
}
}
Unfortunately, there is not much documentation about ControlActiveState and its values in SwiftUI. I experimented with different windows and different states and haven't had active state reported for any of them. I'm not sure what this state signifies. If you come across it, please let me know, you can reach out to me on X @natpanferova.
Since there is not much documentation I'm also not sure why the environment value is called controlActiveState
. Maybe we should update the appearance of custom controls based on this value.
It's worth pointing out that controlActiveState
is different from scenePhase. scenePhase
is available on both iOS and macOS platforms and reports scene lifecycle events rather than its visual state. For example, scenePhase
won't change when we switch between two windows on macOS and one becomes key. It will change, however, if we minimize or close the window.