Swift - 当移动到另一个时,如何从场景中删除滑动手势?

时间:2015-01-11 03:05:51

标签: ios swift sprite-kit uigesturerecognizer

所以我的游戏使用滑动手势,在我的didMoveToView()函数中我初始化了这些手势:

            let swipeRight = UISwipeGestureRecognizer()
            swipeRight.direction = UISwipeGestureRecognizerDirection.Right
            self.view?.addGestureRecognizer(swipeRight)

            let swipeLeft = UISwipeGestureRecognizer()
            swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
            self.view?.addGestureRecognizer(swipeLeft)

            let swipeUp = UISwipeGestureRecognizer()
            swipeUp.direction = UISwipeGestureRecognizerDirection.Up
            self.view?.addGestureRecognizer(swipeUp)

            let swipeDown = UISwipeGestureRecognizer()
            swipeDown.direction = UISwipeGestureRecognizerDirection.Down
            self.view?.addGestureRecognizer(swipeDown)

问题是当我移动到我的GameOver场景时,我轻扫,它会崩溃我的应用程序。我注意到有人发布了类似的东西并将其作为答案

override func willMoveFromView(view: SKView) {
   for recognizer in self.view.gestureRecognizers! {
       self.view.removeGestureRecognizer(recognizer)
   }
}

在切换到游戏结束之前,仍然不太确定如何实现此功能和/或从场景中删除手势。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:10)

以下内容将从视图中删除所有滑动手势识别器:

override func willMoveFromView(view: SKView) {
    if let gestures = view.gestureRecognizers {
        for gesture in gestures {
           if let recognizer = gesture as? UISwipeGestureRecognizer {
                view.removeGestureRecognizer(recognizer)
           }
        }
    }
}

答案 1 :(得分:0)

你正在删除所有类型的手势,试试这个:

if([recognizer isKindOfClass:[UISwipeGestureRecognizer class]]) {
    [self removeGestureRecognizer:recognizer];
}

希望这会有所帮助.. :)

答案 2 :(得分:0)

UIGestureRecognizer替换为UISwipeGestureRecognizer,如果这是您要删除的内容。

extension SKView {
    func removeAllGestureRecognizers() {
        if let objects = gestureRecognizers {
            for object in objects {
                if let gestureRecognizer = object as? UIGestureRecognizer {
                    removeGestureRecognizer(gestureRecognizer)
                }
            }
        }
    }
}