Vergmort
Vergmort

Reputation: 399

How to make a Toggle Button on SpriteKit

I am doing a sound toggle button in SpriteKit, and I'm trying to find out a quick way to do it. I remember that in Cocos2d there was a variable called CCMenuItemToggle that made all the stuff, for example:

CCMenuItemToggle* musicButtonToggle = [CCMenuItemToggle
                                               itemWithItems:[NSArray arrayWithObjects:soundButtonOn,soundButtonOff, nil]
                                               block:^(id sender)
                                               {
                                                   [self stopSounds];
                                               }];

Anyone know a way to do this on SpriteKit?

Upvotes: 4

Views: 1712

Answers (1)

DogCoffee
DogCoffee

Reputation: 19946

Basic Toggle Button Subclassing a SKLabelNode

.h

typedef NS_ENUM(NSInteger, ButtonState)
{
    On,
    Off
};

@interface ToggleButton : SKLabelNode

- (instancetype)initWithState:(ButtonState) setUpState;
- (void) buttonPressed;

@end

.m

#import "ToggleButton.h"

@implementation ToggleButton
{
    ButtonState _currentState;
}

- (id)initWithState:(ButtonState) setUpState
{
    if (self = [super init]) {
        _currentState = setUpState;
        self = [ToggleButton labelNodeWithFontNamed:@"Chalkduster"];
        self.text = [self updateLabelForCurrentState];
        self.fontSize = 30;
    }
    return self;
}

- (NSString *) updateLabelForCurrentState
{
    NSString *label;

    if (_currentState == On) {
        label = @"ON";
    }
    else if (_currentState == Off) {
        label = @"OFF";
    }

    return label;
}

- (void) buttonPressed
{
    if (_currentState == Off) {
        _currentState = On;
    }
    else {
        _currentState = Off;
    }

    self.text = [self updateLabelForCurrentState];
}

@end

Add a Toggle button to your scene

ToggleButton *myLabel = [ToggleButton new];
myLabel = [myLabel initWithState:Off];
myLabel.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
[self addChild:myLabel];

Detect a touch

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch* touch = [touches anyObject];
    CGPoint loc = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:loc];

    if ([node isKindOfClass:[ToggleButton class]]) {
        ToggleButton *btn = (ToggleButton*) node;
        [btn buttonPressed];
    }
}

Upvotes: 6

Related Questions