How could I do something before navigate to other view by NavigationLink?

被刻印的时光 ゝ 提交于 2020-07-09 10:05:45

问题


Let me show the simple source code:

struct ContentView : View {

    @State var isPresented = false
    var body: some View {        
            NavigationView {
                HStack{
                    NavigationLink(destination: MyDetailView(message: "Detail Page #2") ) {
                        Text("Go detail Page #2 >")
                    }
                    .navigationBarTitle("Index Page #1")
                }
            }

    }
}

Before navigate to MyDetailView, I want to do something, for example: save some data, or change some variable...

How could I do that?

It may be a simple question, but I really don't know.

Thanks for your help!


回答1:


I have got a simple method to resolve that:

struct ContentView : View {

    @State var isPresented = false
    var body: some View {        
            NavigationView {
                HStack{
                    NavigationLink(destination: MyDetailView(message: "Detail Page #2") ,isActive: $isPresented) {
                        Text("Go detail Page #2 >")
                            .onTapGesture
                             {
                                 //Do somethings here
                                 print("onTapGesture")
                                 //Navigate
                                 self.isPresented = true
                             }
                    }
                    .navigationBarTitle("Index Page #1")
                }
            }

    }
}



回答2:


You can handle methods from lifecycle using:

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

And:

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

check this tutorial: https://www.hackingwithswift.com/quick-start/swiftui/how-to-respond-to-view-lifecycle-events-onappear-and-ondisappear

So, you can use the .onDisappear to perform any action you need



来源:https://stackoverflow.com/questions/58572063/how-could-i-do-something-before-navigate-to-other-view-by-navigationlink

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!