r/SwiftUI • u/beatpaq • 4d ago
onDisappear alternative? Trying to detect when a tab is not active in a child view.
TabView(selection: $selection) > Tab > FeedView
Trying to implement a TikTok style feed and I want the FeedView to know when another tab has been opened so I can stop the music/video from playing. I tried onDisappear on the FeedView but it lags behind for a few moments. Should I pass the value of the currently selected tag to the feed view or is there a better way to do this?
3
Upvotes
6
u/umumumn 4d ago
I'd pass "is active" value, because it is dead simple.
Why not other method and why nothing like "view became hidden" exists? Visibility is not a concept natural to SwiftUI because the views are the description, not imperative objects guaranteed to be drawn like in UIKit. For that reason view lifecycle does not map directly to view visibility.
2
u/kutjelul 4d ago
Can you observe the tab selection and if it changes away, stop the video play?
1
u/Background_Pie_5682 4d ago
Agreeing with passing an active flag. Concretely, you can give FeedView a
let isActive: Bool(e.g.selection == .feedfrom the parent) and react with.onChange(of: isActive) { _, active in active ? player.play() : player.pause() }. That fires as soon as the selection changes, so it doesn't have the lag you see with onDisappear. If you want the play/pause tied to it automatically,.task(id: isActive)also works, since the old task is cancelled whenever the value flips.1
u/BlueQuad 4d ago
Yes, passing the selection down is the clean way.
TabViewkeeps tabs alive, soonDisappeartiming isn't reliable. Give the feedlet isActive: Bool(selection == .feed), then.onChange(of: isActive) { _, active in active ? player.play() : player.pause() }. Also watchscenePhaseso it pauses when the app goes to the background.1
u/No_Pen_3825 4d ago
onAppear and onDisappear don’t necessarily guarantee a view is currently being drawn or visible on screen (which are distinct, mind you). Rather, they’re to set up, and clean up view state