NEW BOOK! SwiftUI Fundamentals: The essential guide to SwiftUI core concepts and APIs. Learn more ...NEW BOOK! SwiftUI Fundamentals:Master SwiftUI core concepts and APIs. Learn more...
Quick Tip Icon
Quick Tip

Detecting the focused window on macOS in SwiftUI

Previously, I relied on the controlActiveState environment value to check whether a window was focused in SwiftUI on macOS. However, this API has been deprecated since macOS 15.

The replacement is the appearsActive environment value, which is true when the window is focused and false when it's not.

struct ContentView: View {
    @Environment(\.appearsActive) var appearsActive
    
    var body: some View {
        Text("Window is focused: \(appearsActive)")
            .onChange(of: appearsActive) { oldValue, newValue in
                let oldStatus = oldValue ? "active" : "inactive"
                let newStatus = newValue ? "active" : "inactive"
                print("Window focus changed from \(oldStatus) to \(newStatus).")
            }
    }
}

This value is useful for adjusting the appearance of controls or other UI elements when the window becomes inactive. We may also want to trigger actions when focus changes.

I used appearsActive in a settings window to update the state of a control. You can find an example in my previous post: Add launch at login setting to a macOS app.

SwiftUI Fundamentals by Natalia Panferova book coverSwiftUI Fundamentals by Natalia Panferova book cover

Deepen your understanding of SwiftUI!$35

The essential guide to SwiftUI core concepts and APIs

SwiftUI Fundamentalsby Natalia Panferova

  • Explore the key APIs and design patterns that form the foundation of SwiftUI
  • Develop a deep, practical understanding of how SwiftUI works under the hood
  • Learn from a former Apple engineer who worked on widely used SwiftUI APIs

Deepen your understanding of SwiftUI!

The essential guide to SwiftUI core concepts and APIs

SwiftUI Fundamentals by Natalia Panferova book coverSwiftUI Fundamentals by Natalia Panferova book cover

SwiftUI Fundamentals

by Natalia Panferova

$35