简体   繁体   English

如何检测滑动和拖动之间的手势?

[英]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? 但是如何知道那是滑动或平移手势?

@dfd is correct. @dfd是正确的。 You should always use the built-in iOS gesture recognizers for this. 为此,您应始终使用内置的iOS手势识别器。 If apps were to each implement their own logic for determining gestures, iOS would be a very inconsistent experience for users. 如果应用程序各自执行自己的逻辑来确定手势,则iOS对于用户而言将是非常不一致的体验。

Every gesture recognizer is going to be a subclass of UIGestureRecognizer . 每个手势识别器都将是UIGestureRecognizer的子类。 You should read the documentation . 您应该阅读文档

In your case you want UISwipeGestureRecognizer and UIPanGestureRecognizer . 在您的情况下,您需要UISwipeGestureRecognizerUIPanGestureRecognizer

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 . 您不必在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. 识别器会自动将其自身作为参数传递给自定义函数,以便您可以查询state属性等。您应该阅读文档以了解此过程对于每个手势识别器有何不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM