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.

Integrating SwiftUI into UIKit Apps by Natalia Panferova book coverIntegrating SwiftUI into UIKit Apps by Natalia Panferova book cover

Check out our book!

Integrating SwiftUI into UIKit Apps

Integrating SwiftUI intoUIKit Apps

UPDATED FOR iOS 17!

A detailed guide on gradually adopting SwiftUI in UIKit projects.

  • Discover various ways to add SwiftUI views to existing UIKit projects
  • Use Xcode previews when designing and building UI
  • Update your UIKit apps with new features such as Swift Charts and Lock Screen widgets
  • Migrate larger parts of your apps to SwiftUI while reusing views and controllers built in UIKit