4

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!

norains
  • 743
  • 1
  • 5
  • 12

2 Answers2

4

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

    }
}
norains
  • 743
  • 1
  • 5
  • 12
  • This is the correct answer and is a simple and effective way of achieving the goal. – FontFamily Dec 30 '20 at 19:11
  • I've been adding '.onTapGesture' to so many items.....never thought to add it to the text of the NavigationLink. Thank you. Using this to dismiss keyboard prior to navigation....couldn't find another simple solution beforehand. – SPM Mar 16 '23 at 21:45
0

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

Renata Faria
  • 515
  • 6
  • 10
  • Another question: If I have two NavigationList, for example: cancel and save, how could I know which NavigationList I click? – norains Oct 27 '19 at 07:50
  • NavigationLink you mean? You can handle this with a `@State var`. If you click save, you modify it for "save" and the same with cancel. Idk if tha'ts what you want.. sorry, I didn't got your question – Renata Faria Oct 28 '19 at 00:09