Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")}
        }
like image 623
I Kaya Avatar asked Mar 05 '20 15:03

I Kaya


People also ask

How does NavigationLink work SwiftUI?

NavigationLink in SwiftUI allows pushing a new destination view on a navigation controller. You can use NavigationLink in a list or decide to push a view programmatically. The latter enables you to trigger a new screen from a different location in your view.


1 Answers

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

like image 195
Aleksey Potapov Avatar answered Sep 20 '22 15:09

Aleksey Potapov