Search code examples
iosswiftuitapgesturerecognizer

Type 'GameScene' has no member 'handleTap(tapGesture:)'


I have been working on an app with XCode (in version 9.3.1) and was using the Coding iPhone Apps for Kids (https://nostarch.com/iphoneappsforkids/) as a guide to learn how to create games such as the skateboarder game that begins in chapter 14.

I have followed the code, however, has run into an error with using the handleTap(tapGesture:).

      override func didMove(to view: SKView) {
    physicsWorld.gravity = CGVector(dx: 0.0, dy: -6.0)
    physicsWorld.contactDelegate = self

    anchorPoint = CGPoint.zero

    let background = SKSpriteNode(imageNamed: "background")
    let xMid = frame.midX
    let yMid = frame.midY
    background.position = CGPoint(x: xMid, y: yMid)
    addChild(background)

    setupLabels()

    // Set up the player and add her to the scene
    player.setupPhysicsBody()
    addChild(player)

    // Add a tap gesture recognizer to know when the user tapped the screen
    let tapMethod = #selector(GameScene.handleTap(tapGesture:))
    let tapGesture = UITapGestureRecognizer(target: self, action: tapMethod)
    view.addGestureRecognizer(tapGesture)

    // Add a menu overlay with "Tap to play" text
    let menuBackgroundColor = UIColor.black.withAlphaComponent(0.4)
    let menuLayer = MenuLayer(color: menuBackgroundColor, size: frame.size)
    menuLayer.anchorPoint = CGPoint(x: 0.0, y: 0.0)
    menuLayer.position = CGPoint(x: 0.0, y: 0.0)
    menuLayer.zPosition = 30
    menuLayer.name = "menuLayer"
    menuLayer.display(message: "Tap to play", score: nil)
    addChild(menuLayer)
}

It gives the error in

    let tapMethod = #selector(GameScene.handleTap(tapGesture:))

However, further down, I have this code.

     func handleTap(tapGesture: UITapGestureRecognizer) {

        if gameState == .running {

            // Make the player jump if player taps while she is on the ground
            if player.isOnGround {

                player.physicsBody?.applyImpulse(CGVector(dx: 0.0, dy: 260.0))

                run(SKAction.playSoundFileNamed("jump.wav", waitForCompletion: false))
            }
        }
        else {

            // If the game is not running, tapping starts a new game
            if let menuLayer: SKSpriteNode = childNode(withName: "menuLayer") as? SKSpriteNode {

                menuLayer.removeFromParent()
            }

            startGame()
        }
    }

Though I have handleTap under the update method, the error would not remove itself.

If you have a solution to the error code in the title, please let me know.


Solution

  • Change selector & signature to this

    let tapMethod = #selector(GameScene.handleTap(_:))
    

    //

    @objc func handleTap(_ tapGesture: UITapGestureRecognizer) {}