Search code examples
iosswiftuigesturerecognizerswipe

make a lot actions when long swipe SWIFT


i have a left and right Gestore recognizer and i need to do a lot of the same actions when user swipes.

Like user touched screen and swiped a millimeter !ACTION, 1 more milimeter !ACTION, 1 more !ACTION and so on

let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(handleLeftGesture))
        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(handleRightGesture))
 swipeLeft.direction = .left
        swipeRight.direction = .right
    self.addGestureRecognizer(swipeLeft)
        self.addGestureRecognizer(swipeRight)

in my case i change pictures very fast

@objc func handleLeftGesture(sender: UISwipeGestureRecognizer) {
//if distance of swipe 1mm make this action
        if nextImage >= imagesCount - 4 {
            nextImage = 0
        } else {
            nextImage += 4
        }
//repeat action before if he continue swiping
    }

how do i realize it?


Solution

  • As commented above what you are looking for is a Pan gesture. According to documentation one of the differences between Swipe and Pan gestures is that Swipe gestures are discrete, so your action method is called only after the gesture ends successfully. However, Pan gestures are continuous, so your action method is called whenever the touch information changes, giving you a chance to update your content.

    This is the sample code of how to handle a pan gesture. As commented in the code the translation allows you to know how much you moved both in X and Y direction. Negative values for translation.x would mean you moved to the left and positive values would mean you moved to the right.

    var initialCenter = CGPoint()  // The initial center point of the view.
    @IBAction func panPiece(_ gestureRecognizer : UIPanGestureRecognizer) {   
       guard gestureRecognizer.view != nil else {return}
       let piece = gestureRecognizer.view!
       // Get the changes in the X and Y directions relative to
       // the superview's coordinate space.
       let translation = gestureRecognizer.translation(in: piece.superview)
       if gestureRecognizer.state == .began {
          // Save the view's original position. 
          self.initialCenter = piece.center
       }
          // Update the position for the .began, .changed, and .ended states
       if gestureRecognizer.state != .cancelled {
          // Add the X and Y translation to the view's original position.
          let newCenter = CGPoint(x: initialCenter.x + translation.x, y: initialCenter.y + translation.y)
          piece.center = newCenter
       }
       else {
          // On cancellation, return the piece to its original location.
          piece.center = initialCenter
       }
    }