UIGestureRecognizer,从另一个类调用选择器

时间:2017-12-31 03:00:16

标签: ios swift sprite-kit uigesturerecognizer selector

我有两个类都添加UIPinchGestureRecognizer并使用选择器来处理响应手势的代码。注意:手势识别器委托可能与此问题无关,但我将其包含在代码中以防万一。

class GameScene: SKScene, UIGestureRecognizerDelegate {

    override func didMove(to view: SKView) {
        let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(handlePinchFrom))
        pinchGestureRecognizer.delegate = self
        self.view!.addGestureRecognizer(pinchGestureRecognizer)
    }

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

    @objc func handlePinchFrom(_ rec: UIPinchGestureRecognizer) {
        // This method should only be called when pinching in GameScene scene.
    }
}


class Level1: SKScene, UIGestureRecognizerDelegate {

    // Same code here as in GameScene class.

    @objc func handlePinchFrom(_ rec: UIPinchGestureRecognizer) {
        // This method should only be called when pinching in Level scene.
    }
}

GameScene中,handlePinchFrom方法正常调用。用户从GameScene转换为Level1场景后,handlePinchFrom中的Level1方法正常被调用。但是,handlePinchFrom中的GameScene方法在Level1中执行捏合手势时仍会被调用,即使调试视图层次结构中不再显示GameScene

同样,如果用户离开Level1并转换回GameScene,那么当您在{中执行捏合手势时,来自handlePinchFrom的{​​{1}}方法也会被调用{1}}。

我猜这可能是由两个选择器使用相同的名称(handlePinchFrom)引起的。但我尝试给其中一个选择器一个不同的名字,当我期望只调用其中一个时,它们仍会被调用。

有人知道为什么加载Level1后仍然会调用GameScene中的handlePinchFrom方法,即使程序不再运行GameScene类吗?

1 个答案:

答案 0 :(得分:0)

由于0x141E的建议,我修复了我的代码。请参阅下面的更新代码。

我设置了手势识别器并在didMove(to view:)中获取对它的引用。然后我使用引用将其从willMove(from view:)中的场景视图中删除。

现在,在我的应用程序离开游戏场景后,手势识别器不再被调用。

class GameScene: SKScene {
    var pinchGrRef: UIPinchGestureRecognizer?

    override func didMove(to view: SKView) {
        let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(handlePinchFrom))
        self.view!.addGestureRecognizer(pinchGestureRecognizer)
        self.pinchGrRef = pinchGestureRecognizer
    }

    @objc func handlePinchFrom(_ rec: UIPinchGestureRecognizer) {
        // Respond to pinch gesture
    }

    override func willMove(from view: SKView) {
        if pinchGrRef != nil { self.view!.removeGestureRecognizer(pinchGrRef!) }
    }
}