Search code examples
swiftuiswiftui-navigationlink

LazyVGrid onTapGesture navigate to next screen swiftUI


I am quite new to swiftUI. I have created a grid view on tapping on which I want to go to next screen. But somehow I am not able to manage to push to next screen. I am doing like this:

    var body: some View {
    NavigationView {
        ScrollView {
            LazyVGrid(columns: gridItems, spacing: 16) {
                ForEach(viewModel.pokemon) { pokemon in
                    PokemonCell(pokemon: pokemon, viewModel: viewModel)
                        .onTapGesture {
                            NavigationLink(destination: PokemonDetailView(pokemon: pokemon)) {
                                Text(pokemon.name)
                            }
                        }
                }
            }
        }
        
        .navigationTitle("Pokedex")
    }
    
}

Upon doing like this, I am getting a warning stating

Result of 'NavigationLink<Label, Destination>' initializer is unused

Can someone please guide me, how to do this?


Solution

  • .onTapGesture adds an action to perform when the view recognizes a tap gesture. In your case you don't need to use .onTapGesture. If you want to go to another view when cell is tapped you need to write NavigationLink as below.


    NavigationLink(destination: PokemonDetailView(pokemon: pokemon)) {
                                  PokemonCell(pokemon: pokemon, viewModel: viewModel)
                                }
    

    If you want to use .onTapGesture, another approach is creating @State for your tapped cell's pokemon and using NavigationLink's isActive binding. So when user tap the cell it will change the @State and toggle the isActive in .onTapGesture. You may need to add another Stack (ZStack etc.) for this.

    NavigationView {
                  ZStack {
                    NavigationLink("", destination: PokemonDetailView(pokemon: pokemon), isActive: $isNavigationActive).hidden()
                    ScrollView {
                                // ...