iosswiftuiswiftui-navigationlinkswiftui-navigationviewswiftui-navigationstack

Why NavigationLink is not working sometimes, even when we alter the isActive variable?


Have you ever experienced the NavigationLink not working sometimes, but when you scroll the list to the bottom or do something else, the navigation is triggered?

 NavigationView {
      List {
           //.... some views
      }
      NavigationLink(destination: destinationView(), 
                          isActive: $isShowDestination) {
                EmptyView()
      }
 }

Answer: After several attempts, I found that when I tap to push (altering isShowDestination/isActive variable), navigation does not go to the Destination view, but when I scroll list to the bottom, it automatically triggers and goes to the Destination view.

Then I realized that because the List has many views, when I scroll down, an onAppear kind of some event occurs, triggering the NavigationLink to work.

Then I added a VStack and placed the NavigationLink inside the List, and it started working well.

example:

 NavigationView {
      VStack {
           List {
               //.... some views
           }
           NavigationLink(destination: destinationView(), 
                          isActive: $isShowDestination) {
                EmptyView()
           }
      }
 }

I hope this will help at least one of you.🙋


Solution

  • In Your case, you are providing 2 screens in NavigationView

    NavigationView {
        List {                                }
            /*some views*/                    }= List as Screen1
        }                                     }
        
        NavigationLink(                       }
            destination: destinationView(),   }
            isActive: $isShowDestination      }= EmptyView as Screen2
        ) {                                   }
            EmptyView()                       }
        }                                     }
    }
    

    In SwiftUI:
    1). NavigationView should only contain one main home view only.
    2). Try to write All the NavigationLink (specially isActive one) at top.
    3). Remove EmptyView()

    NavigationView {
        VStack {
            NavigationLink(
                destination: destinationView(), 
                isActive: $isShowDestination
            ) { }
            
            List {
                /*some views*/
            }
        }
    }
    

    in your case, VStack is only 'one & only main home view'.
    All "push" work done by it.