functionnavigationswiftuinavigationlink

Is there a way to add an extra function to NavigationLink? SwiftUI


I would like to add an extra function to the NavigationLink.

example code is something like this:

struct ContentView: View {

func yes () {
print("yes")
}

var body: some View {

NavigationView {
NavigationLink(destination: level1()) {

     Text("Next")      
}}}}

I know this doesn't work, but is it possible to do something like this? (It will go to the destination and call the function at the same time)

NavigationLink(destination: level1(), yes()) {Text("Next")}   

I tried putting a button inside the NavigationLink but it didn't work either. When I do this only the function in the button works, NavigationLink doesn't.

NavigationLink(destination: level1())   {
        Button(action: { self.yes() }) 
        { Text("Button")}
        }

Solution

  • Use the onAppear(perform:). This will perform some function on a View's appear.

    struct ContentView: View {
        var body: some View {
            NavigationView {
                NavigationLink(destination: DetailView().onAppear {
                    self.someFunc()
                }) {
                    Text("First Screen")
                }
            }
        }
    
        func someFunc() {
            print("Click")
        }
    }
    
    struct DetailView: View {
        var body: some View {
            Text("Second Screen")
        }
    }