Skiddyflyer Skiddyflyer - 15 days ago 5
Swift Question

Swift Spritekit Adding Button Programaticly

How do I programatically add a button that will run an action when its clicked? What code would be used?

I am new to swift and the new languages, I am used to just adding a button in the storyboard and running an IBAction from there.

Answer

Adding a button in SpriteKit and responding to taps on it is not quite as easy as it is in UIKit. You basically need to create an SKNode of some sort which will draw your button and then check to see if touches registered in your scene are within that node's bounds.

A really simple scene with just a single red rectangle in the center acting as a button would look something like this:

class ButtonTestScene: SKScene {
    var button: SKNode! = nil

    override func didMoveToView(view: SKView) {
        // Create a simple red rectangle that's 100x44
        button = SKSpriteNode(color: SKColor.redColor(), size: CGSize(width: 100, height: 44))
        // Put it in the center of the scene
        button.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));

        self.addChild(button)
    }

    override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
        // Loop over all the touches in this event
        for touch: AnyObject in touches {
            // Get the location of the touch in this scene
            let location = touch.locationInNode(self)
            // Check if the location of the touch is within the button's bounds
            if button.containsPoint(location) {
                println("tapped!")
            }
        }
    }
}

If you need a button that looks and animates like the ones in UIKit, you'll need to implement that yourself; there's nothing built in to SpriteKit.