-1

I am having an issue with a navigation link with a tap gesture in Swift UI. What happens is that once I tap the navigation link, the code works fine, my function on the tap gesture adds the item to the cart and I get redirected to the NavLink destination. The problem is after a millisecond I get transported back to the previous view.

After taping the nav link the view opens, runs the code and then closes.

My navigation link with a tap gesture looks like this:

NavigationLink(destination: CartView(homeData: homeData)){
                Text("Add to Cart")
                    .font(.title2)
                    .fontWeight(.heavy)
                    .foregroundColor(.white)
                    .padding(.vertical)
                    .frame(width: UIScreen.main.bounds.width - 30)
                    .background(LinearGradient(gradient: Gradient(colors: [Color("TopGradientColor"), Color("BottomGradientColor")]), startPoint: .top, endPoint: .bottom))
                    .cornerRadius(15)
        }.simultaneousGesture(TapGesture().onEnded{
            homeData.addToCart(item: item)
        })

I have tried adding a .onTapGestire { ... } to the text item but I still have this issue. I have checked that both things alone work and that it is not an issue of the function or the views.

Thanks to everyone in advance!

  • could you show the code of a complete example that produces your issue, including the surrounding `NavigationView` and the `item`, presumably from a list. – workingdog support Ukraine Jul 02 '22 at 02:20
  • 1
    I suppose that when your simultaneous gesture ends , homeData is updated and then the view is redrawn. This means the navigation is cancelled. – Ptit Xav Jul 02 '22 at 09:08

1 Answers1

0

you could try a different initialiser of NavigationLink, such as:

@State var currentTag: ItemType? // <-- here, adjust ItemType

NavigationLink(destination: CartView(homeData: homeData),
               tag: item, 
               selection: $currentTag) {
    Text("Add to Cart")
        .font(.title2)
        .fontWeight(.heavy)
        .foregroundColor(.white)
        .padding(.vertical)
        .frame(width: UIScreen.main.bounds.width - 30)
        .background(LinearGradient(gradient: Gradient(colors: [Color("TopGradientColor"), Color("BottomGradientColor")]), startPoint: .top, endPoint: .bottom))
        .cornerRadius(15)
}.simultaneousGesture(TapGesture().onEnded {
    print("---> simultaneousGesture")
    homeData.addToCart(item: item)
    self.currentTag = item  // <-- here
})