Jay Patel
Jay Patel

Reputation: 2740

How to detect gesture between swipe and drag?

I want to create one view in main view and apply both swipe and drag (pan) gesture to that view. But how to know that that is swipe or pan gesture?

Upvotes: 2

Views: 4230

Answers (1)

Matthew Seaman
Matthew Seaman

Reputation: 8092

@dfd is correct. You should always use the built-in iOS gesture recognizers for this. If apps were to each implement their own logic for determining gestures, iOS would be a very inconsistent experience for users.

Every gesture recognizer is going to be a subclass of UIGestureRecognizer. You should read the documentation.

In your case you want UISwipeGestureRecognizer and UIPanGestureRecognizer.

Here's an example:

class ViewController: UIViewController {

    override func viewDidLoad() {
        let swipeRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(userSwiped))
        swipeRecognizer.numberOfTouchesRequired = 1
        swipeRecognizer.direction = .left

        let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(userPanned))
        panRecognizer.minimumNumberOfTouches = 1

        view.addGestureRecognizer(swipeRecognizer)
        view.addGestureRecognizer(panRecognizer)
    }

    @objc private func userSwiped(recognizer: UISwipeGestureRecognizer) {

    }

    @objc private func userPanned(recognizer: UIPanGestureRecognizer) {

    }

}

Here, I create the gesture recognizers and add them to whichever view I want. You don't have to do this in viewDidLoad. By setting the target, we are setting which method should be called when the gesture is recognized. The recognizers automatically pass themselves as arguments to your custom functions so that you can query the state property, etc. You should read the documentation to understand how this process differs for each gesture recognizer.

Upvotes: 8

Related Questions