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
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
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.