Search code examples
iosswiftgesture

Swift : setup a Pan Gesture left to right


I would like to set a Pan Gesture and assign it to a view, to make it moving only to the right and to the left according to the movement of the finger with a dynamic animation. I don't know how to do that because I'm beginning, thanks a lot !


Solution

  • Checking a PanGesture direction in swift could look like something like this.

    extension UIPanGestureRecognizer {
    
        func isLeft(theViewYouArePassing: UIView) -> Bool {
            let detectionLimit: CGFloat = 50
            var velocity : CGPoint = velocityInView(theViewYouArePassing)
            if velocity.x > detectionLimit {
                print("Gesture went right") 
                return false
            } else if velocity.x < -detectionLimit {
                print("Gesture went left")
                return true
            }
        }
    }
    
    // Then you would call it the way you call extensions
    var panGesture : UIPanGestureRecognizer
    
    // and pass the view you are doing the gesture on
    panGesture.isLeft(view) // returns true or false
    

    You could also create such a method without extensions as well, but I think this way is really nice.

    Hope this helps anyone trying to find an answer to this!!