programmatically simulate a swipe gesture in Swift

Nicholas Muir picture Nicholas Muir · Aug 15, 2016 · Viewed 10.1k times · Source

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)

Answer

hris.to picture hris.to · Aug 15, 2016

You can create the UIPanGestureRecognizer by yourself and pass it to the wasDragged method. You should check with different values of the translation though:

let gesture = UIPanGestureRecognizer()
gesture.setTranslation(CGPointMake(0, 100), inView: self.view)
wasDragged(gesture)

SWIFT 4.2

 let gesture = UIPanGestureRecognizer()
 gesture.setTranslation(CGPoint(x: 0, y: 100), in: self.view)
 wasDragged(gesture)

Although I asume you need something else. Why do you need to simulate this gesture in the first place?