Search code examples
swiftgesture

Limiting pan gesture to one direction


Would like to have the image only pan upwards.

I have tried to edit the x and y coordinates. Tried to to make a new y variable based on the translation but does not change.

@objc func handleVerticalPan(_ recognizer: UIPanGestureRecognizer)     {
    let translation: CGPoint = recognizer.translation(in: self.view)
    var newY = view.center.y + translation.y
        startingPoint = recognizer.view!.center
        recognizer.view?.superview?.bringSubviewToFront(recognizer.view!)
        if newY > translation.y
        {
            recognizer.view?.center = CGPoint(x: recognizer.view!.center.x, y: recognizer.view!.center.y + translation.y)
            newY = view.center.y + translation.y
            recognizer.setTranslation(CGPoint(x: 0, y: 0), in: self.view)
            //startingPoint = recognizer.view!.center
        }

It will pan up and down but I only want it to go up.


Solution

  • You are comparing the wrong variables, and Y values increase in the downward direction. All you need to check is that transition.y is negative (ie. moving upward):

    Replace this:

    if newY > translation.y
    

    with this:

    if transition.y < 0
    

    In fact, newY isn't really needed at all:

    @objc func handleVerticalPan(_ recognizer: UIPanGestureRecognizer) {
        let translation = recognizer.translation(in: self.view)
        guard let view = recognizer.view else { return }
    
        view.superview?.bringSubviewToFront(view)
    
        // If the movement is upward (-Y direction):
        if translation.y < 0
        {
            view.center = CGPoint(x: view.center.x, y: view.center.y + translation.y)
            recognizer.setTranslation(.zero, in: self.view)
        }
    }
    

    Notes:

    Other changes made:

    1. Used guard to safely unwrap recognizer.view once instead of repeatedly unwrapping it throughout the code.
    2. Replaced CGPoint(x: 0, y: 0) with .zero which Swift infers to be CGPoint.zero since it is expecting a CGPoint.