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;

}
@end

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.

Advertisements

2 comments

  1. Hey, thanks for the article. I’ve been using a similar solution for buttons in SpriteKit. Have you experienced any memory leak using SKShapeNode? Thanks

    1. I haven’t been experiencing any memory leaks from this, but I explicitly release the Node when I exit the scene (though this may not be kosher).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: