How to only run onDisappear when a view is unloaded in SwiftUI

SwiftUI’s view modifier onDisappear is useful for running code when a view goes away. The issue is that it doesn’t differentiate between the view being unloaded and it simply being covered or hidden. Sometimes you want to run specific code when the view is dismissed or unloaded. Simply putting that code in an onDisappear will cause it to run any time a new view is pushed or the tab is changed.

The simple solution to this is to check the view’s presentationMode environment variable.

@Environment(\.presentationMode) var presentationMode

This property is a binding to a PresentationMode object. We can check its isPresented value in onDisappear to determine if the view is loaded or not. If isPresented is true, that means the view is still loaded, it just was just hidden. If isPresented is false, that means the view unloaded.

.onDisappear {
    if presentationMode.wrappedValue.isPresented {
        print("View was hidden")
    } else {
        print("View unloaded")

That’s it! Code in the “View was hidden” block will run any time a view is pushed or the tab of a TabView is changed. Code in the “View unloaded” should only run when the view is dismissed or unloaded.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: