Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 307
norains Avatar asked Nov 01 '25 14:11

norains


1 Answers

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

    }
}
like image 176
norains Avatar answered Nov 04 '25 04:11

norains