简体   繁体   English

如何在SpriteKit上创建一个切换按钮

[英]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. 我正在SpriteKit中做一个声音切换按钮,我正试图找到一个快速的方法来做到这一点。 I remember that in Cocos2d there was a variable called CCMenuItemToggle that made all the stuff, for example: 我记得在Cocos2d中有一个名为CCMenuItemToggle的变量可以创建所有东西,例如:

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

Anyone know a way to do this on SpriteKit? 有人知道在SpriteKit上做这个的方法吗?

Basic Toggle Button Subclassing a SKLabelNode 基本切换按钮子类化SKLabelNode

.h 。H

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

@interface ToggleButton : SKLabelNode

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

@end

.m .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];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM