In SwiftUI for macOS, how can you detect if a view or any ancestor is "hidden"?

Given a View in SwiftUI for macOS, how can I tell if that view is hidden either because it, or any of its ancestor's opacity is 0.0 or the .hidden modifier has been applied?

Presumably I can manually do this with an Environment value on the ancestor view, but I'm curious if this can be done more idiomatically.

An example use case:

I have views that run long-running Tasks via the .task(id:) modifier. These tasks only need to be running if the View itself is visible to the user.

When the View is hidden, the task should stop. When the View reappears, the Task should restart. This happens automatically when Views are created and destroyed, but does not happen when a view is only hidden.

I’m not aware of a built-in way to detect that, though maybe someone here knows a solution I haven’t seen. Personally, I’d avoid trying to read parent state and instead remove the expensive view from the hierarchy so its tasks cancel naturally. If layout space needs to be preserved, I’d swap in a lightweight placeholder view.

@pilotcoder Yeah, I would normally agree to remove the expensive view. On macOS, I find that some "state" can be lost when that happens. (ex: the scroll position in a table, the viewport in a map, the current position in a video player, etc...)

You could create @State variables for as many of those properties as you can (assuming they are accessible), but at least in AppKit where it's possible to hold on to views that have already been created, it's a nice feature to also know if the view is hidden or not.

In SwiftUI for macOS, how can you detect if a view or any ancestor is "hidden"?
 
 
Q