Monitoring key window in SwiftUI on a Mac

My Mac app can run in multiple windows and every window can have multiple tabs AKA “window tabs”. We don’t need to do any development work to support tabs in our Mac apps. Sadly I had to disable window tabs in my SwiftUI project because macOS doesn’t tell me when a user switches tabs.

I use @Environment(\.controlActiveState) to monitor when a user switches between multiple windows. It’s a well-known approach and there are many blog posts describing this technique. The API was added last year in macOS 13. My issues with the tabs are not mentioned in the blog posts I have linked below. The problem is that the value doesn’t update when a user switches from one tab to another.

I also wish .controlActiveState tells us that a window becomes active or key shortly after the window is created. Luckily, this is easy to workaround by adding my code into task(priority:_:) modifier.

Tested on macOS 14 AKA Sonoma, using Xcode 15.1. I will keep this post updated if there’s new information coming to my attention.