How to use UIPanGestureRecognizer to continuously track swipes?

Hello,


I'm working on a game that is controlled by swipes. I have the following function to track pan swipes:


@objc func handlePanFrom(_ recognizer: UIPanGestureRecognizer) {
        if recognizer.state != .cancelled {
            let translation = recognizer.translation(in: recognizer.view)
            // TODO: use the x and y coordinates of endPoint and beginPoint to determine which direction the swipe occurred.
            
            let xDif = translation.x
            let yDif = translation.y
            
            
            if abs(xDif) > abs(yDif) {
                if xDif > 0 {
                    changeDirection(direction: .east)
                    print("change east")
                } else {
                    changeDirection(direction: .west)
                    print("change west")
                }
            } else if abs(yDif) > abs(xDif) {
                if yDif > 0 {
                    changeDirection(direction: .south)
                    print("change south")
                } else {
                    changeDirection(direction: .north)
                    print("change north")
                }
            }

This will track the user's swipes and change the direction effectively, but only if the user lets go of the screen after every swipe. I was wondering, is there a way to "reset" the translation positions every time the direciton is changed so the user does not have to release from the screen after swiping? I tried calling recognizer.setTranslation(CGPointZero, inView: self.view) every time the direction is changed, but that didn't work.

Replies

Sorry, the method I actually tried calling was:

recognizer.setTranslation(CGPoint(x: 0, y: 0), in: self.view)

You could use touchesBegan, –Ended, –Cancelled, and –Moved instead of a gesture recognizer.