3

i need to detect all the swipes left swipe and right swipe including the up slide. I mean i need to detect all the swipes in the 180 degrees area, I'm not sure if I'm clear enough. When I add .up .right and .left it does not detect the diagonals such as left-up, what should I do? Thanks!

Atakan Cavuslu
  • 914
  • 1
  • 9
  • 17

1 Answers1

5

UIPanGestureRecognizer is the way to go for this:

private var panRec: UIPanGestureRecognizer!
private var lastSwipeBeginningPoint: CGPoint?

override func viewDidLoad() {
    panRec = UIPanGestureRecognizer(target: self, action: #selector(ViewController.handlePan(recognizer:)))
    self.view.addGestureRecognizer(panRec)
}

func handlePan(recognizer: UISwipeGestureRecognizer) {
    if recognizer.state == .began {
        lastSwipeBeginningPoint = recognizer.location(in: recognizer.view)
    } else if recognizer.state == .ended {
        guard let beginPoint = lastSwipeBeginningPoint else {
            return
        }
        let endPoint = recognizer.location(in: recognizer.view)
        // TODO: use the x and y coordinates of endPoint and beginPoint to determine which direction the swipe occurred. 
    }
}
WongWray
  • 2,414
  • 1
  • 20
  • 25
  • An 8 way implementation could be as simple as using a `bool` variable set to `false` for each of 4 directions (Up, Down, Left, Right) and setting it `true` when a direction is hit (in this case, determined by the difference between `beginPoint.x` and `endPoint.x` or `beginPoint.y` and `endPoint.y`). If more than one value is true, it's diagonal. – froggomad May 09 '19 at 12:23