Search code examples
swiftui

Is it possible for a NavigationLink to perform an action in addition to navigating to another view?


I'm trying to create a button that not only navigates to another view, but also run a function at the same time. I tried embedding both a NavigationLink and a Button into a Stack, but I'm only able to click on the Button.

ZStack {
    NavigationLink(destination: TradeView(trade: trade)) {
        TradeButton()
    }
    Button(action: {
        print("Hello world!") //this is the only thing that runs
    }) {
        TradeButton()
    }
}

Solution

  • You can use .simultaneousGesture to do that. The NavigationLink will navigate and at the same time perform an action exactly like you want:

    NavigationLink(destination: TradeView(trade: trade)) {
        Text("Trade View Link")
    }.simultaneousGesture(TapGesture().onEnded {
        print("Hello world!")
    })
    

    Note: I wrote this answer back when I was new to SwiftUI. I don't use this technique anymore because I think this is a pretty hacky solution. You can still use this if your use case absolutely needs this, but please test your app carefully if you do. As mentioned by others, this technique will not work within a List.