Skip to content

Instantly share code, notes, and snippets.

@ecto
Created November 19, 2014 01:20
Show Gist options
  • Save ecto/7abc1655d1019f372299 to your computer and use it in GitHub Desktop.
Save ecto/7abc1655d1019f372299 to your computer and use it in GitHub Desktop.
Quick SKLabelNode-based button for Sprite Kit
SKLabelButton *button = [SKLabelButton initWithCallback:^{
NSLog(@"touched");
}];
button.text = @"retry";
button.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
[self addChild:button];
#import <SpriteKit/SpriteKit.h>
@interface SKLabelButton : SKLabelNode
@property (copy, nonatomic) void (^callback)();
@property (strong, nonatomic) UIColor *mainColor;
@property (strong, nonatomic) UIColor *highlightColor;
@property (nonatomic) bool touchWasCancelled;
+(instancetype)initWithCallback:(void (^)())callback;
@end
#import "SKLabelButton.h"
@implementation SKLabelButton
@synthesize callback = _callback;
@synthesize highlightColor;
@synthesize mainColor;
@synthesize touchWasCancelled;
+(SKLabelButton *)initWithCallback:(void (^)())callback {
SKLabelButton *button = [[SKLabelButton alloc] init];
[button setCallback:callback];
return button;
}
-(id)init {
if (self = [super init]) {
[self setUserInteractionEnabled:true];
[self setHighlightColor:[UIColor yellowColor]];
}
return self;
}
-(void)highlight {
[self setMainColor:self.fontColor];
[self setFontColor:highlightColor];
}
-(void)dehighlight {
[self setFontColor:mainColor];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
touchWasCancelled = false;
[self highlight];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint location = [[touches anyObject] locationInNode:self.parent];
if (!CGRectContainsPoint(self.frame, location)) {
touchWasCancelled = true;
[self dehighlight];
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self dehighlight];
if (touchWasCancelled) {
return;
}
CGPoint location = [[touches anyObject] locationInNode:self.parent];
if (CGRectContainsPoint(self.frame, location)) {
_callback();
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment