Atakan Cavuslu
Atakan Cavuslu

Reputation: 954

Swift UISwipeGestureRecognizer how to detect diagonal swipes?

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!

Upvotes: 3

Views: 1132

Answers (1)

WongWray
WongWray

Reputation: 2566

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. 
    }
}

Upvotes: 5

Related Questions