一个视图上有两个UIGestureRecognizer?

时间:2017-09-29 15:32:59

标签: swift uigesturerecognizer

我正在使用spriteKit。我不知道这是否重要。我在didMove(toView)中初始化了两个UIGestureRecognizer到我的视图:

let longPress = UILongPressGestureRecognizer()
longPress.minimumPressDuration = CFTimeInterval(0.0)
longPress.addTarget(self, action: #selector(self.longPressGesture(longpressGest:)))
self.view?.addGestureRecognizer(longPress)

let swipeUp = UISwipeGestureRecognizer()
swipeUp.direction = UISwipeGestureRecognizerDirection.up
swipeUp.addTarget(self, action: #selector(self.swipeUpGesture(swipe:)))
self.view?.addGestureRecognizer(swipeUp)

我的问题是只调用了第一个gestureRecognizer(longpressGest)。当我删除第一个GestureRecognizer时,swipeGestureRecognizer确实有效。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

您需要将游戏场景视图设为手势识别器的代表。您还需要实现其方法shouldRecognizeSimultaneouslyWith,如圣诞节提到的那样:

因此,在您的游戏场景声明中,只需添加UIGestureRecognizerDelegate

class GameScene: SKScene, SKPhysicsContactDelegate, UIGestureRecognizerDelegate {

在你的didMove(查看:SKView)方法中设置其委托:

let longPress = UILongPressGestureRecognizer()
longPress.delegate = self
longPress.minimumPressDuration = 0
longPress.addTarget(self, action: #selector(longPressGesture))
view.addGestureRecognizer(longPress)

let swipeUp = UISwipeGestureRecognizer()
swipeUp.delegate = self
swipeUp.direction = .up
swipeUp.addTarget(self, action: #selector(swipeUpGesture))
view.addGestureRecognizer(swipeUp)

同样在Swift 4中,您需要将@objc添加到您的方法

@objc func longPressGesture(_ longPress: UILongPressGestureRecognizer) {
    print("longPressGesture")
}

@objc func swipeUpGesture(_ swipeUp: UISwipeGestureRecognizer) {
    print("swipeUpGesture")
}

不要忘记添加方法shouldRecognizeSimultaneouslyWith,正如xmasRights已经提到的那样:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    print("shouldRecognizeSimultaneouslyWith")
    return true
}

答案 1 :(得分:1)

您还可以使用相同的手势识别器,并在此功能的两个手势之间进行区别

答案 2 :(得分:0)

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool 
{
    return true
}

https://developer.apple.com/documentation/uikit/touches_presses_and_gestures/coordinating_multiple_gesture_recognizers/allowing_the_simultaneous_recognition_of_multiple_gestures