John Sorensen
John Sorensen

Reputation: 960

Swift onTapGesture with NavigationLink

I want to perform a function when a certain NavigationLink is tapped / touched. I assume that .onTapGesture or something like it would be useful, but when I add .onTapGesture it never triggers upon touching my NavigationLink. Do I need to use a different event handler or is something else wrong?

Sample code:

struct ExampleView: View {
    var body: some View {
        NavigationView() {
            NavigationLink(destination: Text("Destination")) {
                Text("Navigate")
            }
            .onTapGesture {
                print("Tapped")
            }
        }
    }
}

Upvotes: 2

Views: 1573

Answers (1)

Umair Khan
Umair Khan

Reputation: 1301

You can set binding to isActive Parameter of Navigation link and then observe its value using onChange to achieve what you're looking for:

struct ContentView: View {

@State private var isSelected: Bool = false
@State var color: Color = Color.red

var body: some View {
    NavigationView() {
        NavigationLink(
            destination: Text("Destination"),
            isActive: $isSelected,
            label: {
                Text("Navigate")
            }
        )
        .onChange(of: isSelected, perform: { value in
            color = Color.blue
        })
        .background(color)
    }
}

}

Upvotes: 2

Related Questions