Tutorial: Making a Label Button (thing) with SpriteKit

So, I recently found out that Spritekit is kind of lame and sucks while still being amazingly easy to use, but anyways, that's beside the point. So I was having a hard time figuring out how to make a decent button in SpriteKit without using UIButton (since this seems to cause issues in SpriteKit). Anyways, it took me a while and a few stack overflow answers to find a decent solution. If you're looking for a fully functioning Button like UIButton, I suggest this response on StackOverflow courtesy of some person named Graf. Anyways, if you don't really need that or want to make the button solely programmatically, you can do something like this (it's pretty messy, so you should probably clean it up first). 

#import "SKLabelWithBackground.h"

@implementation SKLabelWithBackground

+(SKShapeNode *) getLabelWithText:(NSString *) text andFontColor:(SKColor *)fontColor andFont:(NSString *)font andBackgroundColor:(SKColor*) color andSize:(CGSize)size{
    SKLabelNode *label = [[SKLabelNode alloc]initWithFontNamed:font];
    label.text = text;
    label.fontSize = 20;
    label.name = @"labelButton";
    label.fontColor = fontColor;

    SKShapeNode* background = [SKShapeNode node];
    [background setPath:CGPathCreateWithRoundedRect(CGRectMake(-size.width/2, -size.height/2, size.width, size.height), 4, 4, nil)];
    background.strokeColor = background.fillColor = color;
    [background addChild:label];
    label.position = CGPointMake(0, -label.frame.size.height/2);

    return background;


So using ShapeNode allows you to get rounded edges and creates that button-esque background rectangle behind an SKLabel. This may not be the ideal solution, but it's one that I've found works pretty decently and doesn't have TOO much overhead. Anyways, if you have a better solution, please comment and let me know, I'll update the post.

Written on August 16, 2014