Ben Ayers Ben Ayers - 2 months ago 40
Swift Question

How do I code for gestures in a SKScene in Swift?

I am in the process of learning to develop iOS apps in Swift and I am currently tasked with coding for different swipe gestures. I looked up a few things in the documentation, and finally wrote this:

class GameScene: SKScene {

override func didMove(to view: SKView) {

let down = SKAction.moveBy(x: 0, y: 20, duration: 1)

let sprite = SKSpriteNode(imageNamed: "logo")
sprite.position = CGPoint(x: 0, y: 0)

func swipedDown(gesture:UIGestureRecognizer) {
sprite.run(down)
}

let swipeDown = UISwipeGestureRecognizer(target: self, action: Selector(("swipedDown:")))
swipeDown.direction = .down
view.addGestureRecognizer(swipeDown)
}

}


Upon swiping down in the resulting app, however, I receive an "unrecognized selector sent to instance" error. I've tried a few different things to fix it, but nothing is working.

I am using Xcode 8 GM with Swift 3.

Answer

You ned to update your code to the following to make it work with Swift 3.

let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(swipedDown(_:)))
swipeDown.direction = .down
view.addGestureRecognizer(swipeDown)

func swipedDown(_ sender: UISwipeGestureRecognizer){
     print("Swiped down")
}
Comments