Quick Tip Icon
Quick Tip

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.

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Level up your Swift skills!$35

100+ tips to take your Swift code to the next level

Swift Gemsby Natalia Panferova

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms

Level up your Swift skills!

100+ tips to take your Swift code to the next level

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Swift Gems

by Natalia Panferova

$35