Search code examples
iosswiftuiswipegesturerecognizer

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!


Solution

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