簡體   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