子类化 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
在场景中添加切换按钮
ToggleButton *myLabel = [ToggleButton new];
myLabel = [myLabel initWithState:Off];
myLabel.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
[self addChild:myLabel];
检测触摸
-(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];
}
}