Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

programmatically simulate a swipe gesture in Swift

I am implementing a gesture recognizer for swiping in Swift. I wan to be able to simulate the flinging of the card (programmatically swipe the view).

I assumed there would be a built in function for this but all I have found is one for tap gesture not swipe gesture.

This is how I am implementing the swipe gesturing:

  let gesture = UIPanGestureRecognizer(target: self, action: Selector("wasDragged:"))
    cardView.addGestureRecognizer(gesture)
    cardView.userInteractionEnabled = true
}

func wasDragged (gesture: UIPanGestureRecognizer) {        
    let translation = gesture.translationInView(self.view)
    let cardView = gesture.view!

    // Move the object depending on the drag position
    cardView.center = CGPoint(x: self.view.bounds.width / 2 + translation.x,
                              y:  self.view.bounds.height / 2 + translation.y)
like image 466
Nicholas Muir Avatar asked Jun 03 '26 02:06

Nicholas Muir


1 Answers

You can't simulate a gesture recognizer in its full implications (I mean, you can't actually make iOS think it's a real user action).

You can, however, fool your own code making it act as if it were a real swipe. For that, you need to create a gesture recognizer first:

var gestureRecognizerSwipeRight = UISwipeGestureRecognizer(target: self, action: "activatedGestureRecognizer:")
gestureRecognizerSwipeRight.direction = UISwipeGestureRecognizerDirection.Right
yourView.addGestureRecognizer(gestureRecognizerSwipeRight)

And then pass it directly to your action:

// Some other place in your code
self.activatedGestureRecognizer(gesture: gestureRecognizerSwipeRight)

Your activatedGestureRecognizer(gesture:) method should be something like:

func activatedGestureRecognizer(gesture: UIGestureRecognizer) {
    if let gestureRecognizer = gesture as? UIGestureRecognizer {

        // Here you can compare using if gestureRecognizer == gestureRecognizerSwipeRight
        // ...or you could compare the direction of the gesture recognizer.
        // It all depends on your implementation really.

        if gestureRecognizer == gestureRecognizerSwipeRight {
            // Swipe right detected
        }
    }
}

In fairness, I don't see any real gain in doing it this way. It should be a lot better to simply do the action associated with the swipe instead of actually simulating the gesture recognizer.

If you need, for instance, to animate your card while swipping, why don't you simply disable the user interaction on your card view and animate it programmatically?

like image 181
Alejandro Iván Avatar answered Jun 06 '26 15:06

Alejandro Iván



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!