12

我正在开发一个使用平移手势和滑动手势的应用程序。因此,每次我执行滑动手势时,总是会调用 Pan Gesture 中的方法,而不会调用 Swipe Gesture 方法。

所有手势方法之间是否有任何优先级?

4

3 回答 3

15

您可以通过实现UIGestureRecognizerDelegate协议的以下方法来并行调用它们:

- (BOOL)gestureRecognizer:(UIPanGestureRecognizer *)gestureRecognizer 
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UISwipeGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}
于 2012-04-14T13:33:29.077 回答
9

类上有一个UIGestureRecognizer名为“cancelsTouchesInView”的属性,默认为YES. 这将导致取消任何挂起的手势。Pan 手势首先被识别,因为它不需要“touch up”事件,因此它取消了 Swipe 手势。

如果您希望两种手势都能被识别,请尝试添加:

[yourPanGestureInstance setCancelsTouchesInView:NO];

于 2011-02-02T23:16:02.723 回答
2

优先刷卡

你可以优先使用一个UIGestureRecognizerwith require(toFail:)方法。

@IBOutlet var myPanGestureRecognizer: UIPanGestureRecognizer!
@IBOutlet var mySwipeGestureRecognizer: UISwipeGestureRecognizer!

myPanGesture.require(toFail: mySwipeGestureRecognizer)

现在,只有在滑动失败时,您的平移才会执行。


平底锅做一切

如果滑动平移手势识别器不能很好地使用此设置,您可以将所有逻辑滚动到平移手势识别器中以获得更多控制。

let minHeight: CGFloat = 100
let maxHeight: CGFloat = 700
let swipeVelocity: CGFloat = 500
var previousTranslationY: CGFloat = 0

@IBOutlet weak var cardHeightConstraint: NSLayoutConstraint!

@IBAction func didPanOnCard(_ sender: Any) {

    guard let panGesture = sender as? UIPanGestureRecognizer else { return }

    let gestureEnded = bool(panGesture.state == UIGestureRecognizerState.ended)
    let velocity = panGesture.velocity(in: self.view)

    if gestureEnded && abs(velocity.y) > swipeVelocity {
        handlePanOnCardAsSwipe(withVelocity: velocity.y)
    } else {
        handlePanOnCard(panGesture)
    }
} 

func handlePanOnCard(_ panGesture: UIPanGestureRecognizer) {

    let translation = panGesture.translation(in: self.view)
    let translationYDelta = translation.y - previousTranslationY

    if abs(translationYDelta) < 1 { return } // ignore small changes

    let newCardHeight = cardHeightConstraint.constant - translationYDelta

    if newCardHeight > minHeight && newCardHeight < maxHeight {
        cardHeightConstraint.constant = newCardHeight
        previousTranslationY = translation.y
    }

    if panGesture.state == UIGestureRecognizerState.ended {
        previousTranslationY = 0
    }
}

func handlePanOnCardAsSwipe(withVelocity velocity: CGFloat) {
    if velocity.y > 0 {
        dismissCard() // implementation not shown
    } else {
        maximizeCard() // implementation not shown
    }
}

这是上述代码的演示。

在此处输入图像描述

于 2018-01-13T00:27:49.833 回答