Using a button from a view controller in a SpriteKit scene file

I am using SpriteKit to make a simple tapper app as a test because I am still a beginner with Swift. I have two buttons on one side of the screen that two people can tap to see who can tap faster. I also have a little SpriteKit ball on the other side of the screen that I want to move in the direction of the button tapped, so whoever taps the fastest, gets the ball to their goal. I want to have the buttons in a view controller, not create them with code.


My question is: How can I link those two buttons to my GameScene.swift file while still keeping them on the view controller.


Accepted Reply

You Can create a UIButton with yourSelector method e.g.:


let button = UIButton.init(type: UIButtonType.custom)

button.setBackgroundImage(UIImage.init(named: "Home"), for: UIControlState())

button.setBackgroundImage(UIImage.init(named: "Home2"), for: UIControlState.highlighted)

button.frame = CGRect(x: 10, y: 10, width: 50, height: 50)

button.addTarget(self, action:#selector(yourSelector), for: .touchUpInside)


and then add it to an SKScene with:


self.view?.addSubview(button)



It makes you life more complicated running UIKit and SpriteKit together but it sometimes does the job.

Replies

Wait, why not just create the buttons in Sprite Kit? That would be a lot easier.

You Can create a UIButton with yourSelector method e.g.:


let button = UIButton.init(type: UIButtonType.custom)

button.setBackgroundImage(UIImage.init(named: "Home"), for: UIControlState())

button.setBackgroundImage(UIImage.init(named: "Home2"), for: UIControlState.highlighted)

button.frame = CGRect(x: 10, y: 10, width: 50, height: 50)

button.addTarget(self, action:#selector(yourSelector), for: .touchUpInside)


and then add it to an SKScene with:


self.view?.addSubview(button)



It makes you life more complicated running UIKit and SpriteKit together but it sometimes does the job.