处理多个GestureRecognizers

时间:2017-01-29 06:26:15

标签: swift sprite-kit uigesturerecognizer skspritenode uitapgesturerecognizer

我遇到了一个理解UIGestureRecognizers的问题。我现在的目标是让一组GestureRecognizer执行不同的任务,例如:

override func viewDidLoad() {
    mainScene = GameScene(size: self.view.bounds.size)
    main = view as! SKView

    mainScene.panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(shiftView(recognizer:)))
    main.addGestureRecognizer(mainScene.panRecognizer)

    mainScene.tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(testTap(recognizer:)))
    main.addGestureRecognizer(mainScene.tapRecognizer)

    mainScene.pinchRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(zoomView(recognizer:)))
    main.addGestureRecognizer(mainScene.pinchRecognizer)

这是我的游戏视图控制器,我在其中处理诸如在地图上平移,缩放和点击地图图块等操作。但我也希望能够使用UITapGestureRecognizer移动精灵,所以我也在我的GameScene中创建了这个精灵:

if startGame == true{
            self.startGame()
            for node in (self.tempGameBoard.landShipLayer.children as? Array<landship>)! {

                node.landShipInteraction = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))
                parentViewController.view.addGestureRecognizer(node.landShipInteraction)
            }
        }

在这种情况下,landShip代表屏幕上的精灵,我想通过手势识别器与之互动。

我的问题是,如果我添加第二组识别器,则攻丝操作会完全没有响应。我仍然可以缩放和平移,但我不希望在地图图块上出现我所期望的点击行为。我觉得好像缺少对手势识别器如何工作的理解。

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:7)

UIGestureRecognizerDelegate有一个特殊的功能,可以同时识别同一个对象上的几个手势,这样就可以了。

1)将UIViewController设置为符合UIGestureRecognizerDelegate

2)实现以下功能:

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

    if (gestureRecognizer == mainScene.panRecognizer || gestureRecognizer == mainScene.pinchRecognizer) && otherGestureRecognizer == mainScene.tapRecognizer {
        return true
    }
    return false
}

在这个特定的例子中,我们允许在平移和捏合的同时触发轻击手势。

3)然后只需将代表分配到平移和捏手势识别器:

override func viewDidLoad() {
    // your code...

    // Set gesture recognizers delegates
    mainScene.panRecognizer.delegate = self
    mainScene.pinchRecognizer.delegate = self
}