繁体   English   中英

手势方法(Pan Gesture和Swipe Gesture)之间是否有任何优先条件?

[英]Is there any priority condition between gesture methods (Pan Gesture and Swipe Gesture)?

我正在开发一个应用程序,我使用了Pan Gesture以及Swipe Gesture。 因此,每次我执行Swipe Gesture时,Pan手势中的方法总是被调用,并且Swipe Gesture方法不会被调用。

所有的手势方法之间有没有优先权?

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

- (BOOL)gestureRecognizer:(UIPanGestureRecognizer *)gestureRecognizer 
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UISwipeGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

UIGestureRecognizer类上有一个名为“cancelsTouchesInView”的属性,默认为YES 这将导致任何待处理的手势被取消。 Pan手势首先被识别,因为它不需要具有“修饰”事件,因此它取消了滑动手势。

如果您想要识别两种手势,请尝试添加:

[yourPanGestureInstance setCancelsTouchesInView:NO];

优先刷卡

您可以使用require(toFail:)方法优先使用UIGestureRecognizer

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

以下是上述代码的演示。

在此输入图像描述

暂无
暂无

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

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