我正在开发一个应用程序,我使用了Pan Gesture以及Swipe Gesture。因此,每次我执行Swipe Gesture时,Pan手势中的方法总是被调用,而Swipe Gesture方法不会被调用。
所有手势方法之间是否有任何优先权?
答案 0 :(得分:14)
您可以通过实施UIGestureRecognizerDelegate
协议的以下方法并行调用它们:
- (BOOL)gestureRecognizer:(UIPanGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UISwipeGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
答案 1 :(得分:9)
UIGestureRecognizer
类上有一个名为“cancelsTouchesInView”的属性,默认为YES
。这将导致任何待处理的手势被取消。 Pan手势首先被识别,因为它不需要有“修饰”事件,所以它取消了滑动手势。
如果您想要识别两种手势,请尝试添加:
[yourPanGestureInstance setCancelsTouchesInView:NO];
答案 2 :(得分:2)
优先刷卡
您可以使用UIGestureRecognizer
方法优先require(toFail:)
。
@IBOutlet var myPanGestureRecognizer: UIPanGestureRecognizer!
@IBOutlet var mySwipeGestureRecognizer: UISwipeGestureRecognizer!
myPanGesture.require(toFail: mySwipeGestureRecognizer)
现在,只有在滑动失败时才会执行 pan 。
将 pan 用于所有内容
如果滑动和 pan 手势识别器不能很好地使用此设置,您可以将所有逻辑滚动到 pan 手势识别器可以更好地控制。
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
}
}
以上是代码的演示。