如何在SwiftUI中检测是否返回到NavigationView的根视图?

时间:2019-11-23 11:20:47

标签: ios swiftui

我看到“ ContentView出现了!”仅是第一次发送消息/ onAppear似乎被称为

是否可以通过其他任何方式检测到返回根目录?

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!")
        }
    }
}

2 个答案:

答案 0 :(得分:1)

NavigationViewview个之间保持不变。因此,当您在它们之间推动并弹出时,它们实际上并不是appeardisappear。因此,您需要在 NavigationView的内容上设置modifier不要自行设置NavigationView

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

    .onAppear { print("ContentView appeared!") }
    .onDisappear { print("ContentView disappeared!") }
}

答案 1 :(得分:0)

找到了愚蠢的解决方案,但是它可以工作。只需在根视图内将onAppear()添加到VStack

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