0

Currently, I'm building a card swipe view similar like tinder. I also want to add a slight delay between the swipes, that the user can't swipe fast through the cards. The delay should be one second. However, this is not working as I want. Basically, it's not working at all.

This is what I've done so far:

     @State private var offset: CGSize = .zero
        @State var swipeDelay: Bool = true
    
     var body: some View {
            ZStack {
                VStack {
                    ScrollView {
                        VStack {
                            Image("Image")
                                .resizable()
                        }
                    }
                }
                .frame(width: UIScreen.main.bounds.width - 16, height: UIScreen.main.bounds.height - 200)
                .background(.white)
                .cornerRadius(20)
                .offset(x: offset.width, y: 0)
                .gesture(
                    DragGesture(minimumDistance: 10)
                        .onChanged(setOffset)
                        .onEnded(swipeLogic)
                )
            }
        }
    
    private func setOffset(_ value: DragGesture.Value) {
            if swipeDelay {
                    offset = value.translation
                }
            }
    
     private func swipeLogic(_ value: DragGesture.Value) {
            let velocity = value.predictedEndTranslation.width
            let translationWidth = value.translation.width
            withAnimation(.linear(duration: 0.2)) {
                if translationWidth < 0 && velocity < -350 && swipeDelay {
                    // Remove
                    offset = CGSize(width: -500, height: 0)
                    removeSwipe()
                } else if translationWidth > 0 && velocity > 350 && swipeDelay {
                    // Add
                    offset = CGSize(width: 500, height: 0)
                    removeSwipe()
                } else if translationWidth < -110 && swipeDelay {
                    // Remove
                    offset = CGSize(width: -500, height: 0)
                    removeSwipe()
                } else if translationWidth > 110 && swipeDelay {
                    // Add
                    offset = CGSize(width: 500, height: 0)
                    removeSwipe()
                } else {
                    offset = .zero
                }
            }
        }



private func removeSwipe() {
        swipeDelay = false
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                        swipeDelay = true
   }
 }

The @State property changed to false but for some reason the if statement is always true, even if I don't set the swipeDelay to true in the DispatchQueue.

adri567
  • 533
  • 5
  • 20

0 Answers0