Skip to main content

How to respond to view lifecycle events - onAppear() and onDisappear()

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to respond to view lifecycle events - onAppear() and onDisappear() 관련

SwiftUI by Example

Back to Home

How to respond to view lifecycle events: onAppear() and onDisappear() | SwiftUI by Example

How to respond to view lifecycle events: onAppear() and onDisappear()

Updated for Xcode 15

SwiftUI gives us equivalents to UIKit's viewDidAppear() and viewDidDisappear() in the form of onAppear() and onDisappear(). You can attach any code to these two events that you want, and SwiftUI will execute them when they occur.

As an example, this creates two views that use onAppear() and onDisappear() to print messages, with a navigation link to move between the two:

struct ContentView: View {
    var body: some View {
        NavigationStack {
            VStack {
                NavigationLink {
                    DetailView()
                } label: {
                    Text("Hello World")
                }
            }
            .onAppear {
                print("ContentView appeared!")
            }
            .onDisappear {
                print("ContentView disappeared!")
            }
        }
    }
}

struct DetailView: View {
    var body: some View {
        VStack {
            Text("Second View")
        }
        .onAppear {
            print("DetailView appeared!")
        }
        .onDisappear {
            print("DetailView disappeared!")
        }
    }
}

When that code runs you should be able to move between the two views and see messages printed in your Xcode debug console.

Similar solutions…
How to detect and respond to key press events | SwiftUI by Example

How to detect and respond to key press events
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
All SwiftUI property wrappers explained and compared | SwiftUI by Example

All SwiftUI property wrappers explained and compared
How to use Instruments to profile your SwiftUI code and identify slow layouts | SwiftUI by Example

How to use Instruments to profile your SwiftUI code and identify slow layouts
Building a menu using List | SwiftUI by Example

Building a menu using List

이찬희 (MarkiiimarK)
Never Stop Learning.