Reputation: 121
I'm trying to use a UISwipeGestureRecognizer
so it executes a function when the user swipes right on the screen in an SKScene
. This is my code
I declare it, at the top of the scene.
let swiperight = UISwipeGestureRecognizer();
In the viewDidLoad()
function
swiperight.addTarget(self, action: #selector(GameScene.swipedRight));
swiperight.direction = .right;
self.view?.addGestureRecognizer(swiperight);
and then the function to be executed
@objc func swipedRight() {
print("Object has been swiped right")
}
However, when I run my app and swipe right on the scene, nothing happens, there is no console output whatsoever.
I'm using swift 4, SpriteKit and Xcode 9.2. I'm running the app on my iPhone 6s running the latest non-beta IOS.
Upvotes: 1
Views: 1523
Reputation: 563
Try conforming your SKScene to UIGestureRecognizerDelegate
and setting the swiperight.delegate
property to your scene. This will make sure that even though you are adding the gesture recognizer to you view, the handling of the gesture is "delegated" to your Scene.
Upvotes: 0
Reputation: 939
You should be presenting your scene like so:
Inside your viewcontroller, declare your scenes at the top E.G.
var mainMenu: MainMenu?
Override the viewDidLoad method and present your scene as so: (where your SKScene file is called MainMenu.sks)
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
mainMenu = MainMenu(fileNamed: "MainMenu")
mainMenu?.scaleMode = .fill
view.presentScene(mainMenu)
}
}
Make sure the scene your presenting is of type SKScene
import SpriteKit
import GameplayKit
class MainMenu: SKScene {
}
Make sure your viewControllers view is of type SKView. For example my storyboard looks like so.
After the scene is presented, set up your gesture recognizer in the didMoveTo method as this is called after the scene is presented which is what you want. Whereas viewDidLoad is called before the view is presented.
If you don't have an sks file then you will have to present your scene as:
scene = MainMenu(size: (view.bounds.size))
and the scene you are presenting will have to look like:
class MainMenu: SKScene {
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder) is not used in this app")
}
override init(size: CGSize) {
super.init(size: size)
anchorPoint = CGPoint(x: 0.5, y: 0.5)
//Setup your sknodes in here.
}
override func didMove(to view: SKView) {
let swipeRight = UISwipeGestureRecognizer(target: self,
action:#selector(swipedRight))
swipeRight.direction = .right
view.addGestureRecognizer(swipeRight)
}
@objc func swipedRight(sender:UISwipeGestureRecognizer){
print("swiped right")
}
}
Upvotes: 1