Swift - How to remove swipe gesture from scene when moving to another one?

孤街醉人 提交于 2020-01-21 03:46:25

问题


So my game uses swipe gestures, in my didMoveToView() function I have these gestures initialized:

            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)

Problem is when I move to my GameOver scene, and I swipe, it crashes my app. I noticed someone had posted something similar and got this as an answer

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

Still not quite sure how to implement this and/or remove the gestures from the scene before switching to game over. Can anyone help?


回答1:


The following removes all swipe gesture recognizers from the view:

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



回答2:


You are removing all kind of gesture, try this:

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

Hope this helps.. :)




回答3:


Replace UIGestureRecognizer with UISwipeGestureRecognizer if that's what you want to remove.

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


来源:https://stackoverflow.com/questions/27883575/swift-how-to-remove-swipe-gesture-from-scene-when-moving-to-another-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!