Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect return to the root view of the NavigationView in SwiftUI?

Tags:

ios

swiftui

I see "ContentView appeared!" message only first time/ onAppear seems to be called ones

Is it possible to detect return to the root in any other way?

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: DetailView()) {
                    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!")
        }
    }
}

like image 548
Igor Samtsevich Avatar asked Dec 31 '22 11:12

Igor Samtsevich


1 Answers

NavigationView is persist between views. So it's not actually appear and disappear when you push and pop between them. So you need to set the modifiers on the NavigationView's content, NOT the NavigationView it self:

NavigationView {
    NavigationLink(destination: DetailView()) { Text("Hello World") }

    .onAppear { print("ContentView appeared!") }
    .onDisappear { print("ContentView disappeared!") }
}
like image 109
Mojtaba Hosseini Avatar answered Jan 04 '23 04:01

Mojtaba Hosseini