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.