2

I have an SKLabelNode within an SKSpiteNode within yet one more SKSpriteNode. Purpose is to create a graphic with a blank button on it and then text for that button. I am able to create this but later in my code I want to change the text of this Label Node and I can't seem to do it.

SKSpriteNode * barStart = [SKSpriteNode spriteNodeWithTexture:[SKTexture textureWithImageNamed:baseColor]];

barStart.name=barName;

SKSpriteNode * playPauseButton = [SKSpriteNode spriteNodeWithTexture:[SKTexture textureWithImageNamed:@"button"]];
playPauseButton.name=[NSString stringWithFormat: @"%@-playPauseButton",barName];
playPauseButton.position=CGPointMake( playPauseButton.frame.size.width*2.2, 0);
playPauseButton.alpha=0;

[barStart addChild:playPauseButton];


SKLabelNode * playPauseLabel = [SKLabelNode labelNodeWithFontNamed:@"HelveticaNeue-Thin"];
playPauseLabel.name=[NSString stringWithFormat: @"%@-playPauseButtonLabel",barName];

NSLog(@"playPauseLabel.name : %@",playPauseLabel.name);
playPauseLabel.position=CGPointMake(0,-5);
playPauseLabel.fontSize = 10;
playPauseLabel.horizontalAlignmentMode=SKLabelHorizontalAlignmentModeCenter;

playPauseLabel.fontColor = [SKColor grayColor];
playPauseLabel.text=@"start/stop";

[barStart addChild:playPauseLabel];

I am trying to change as follows:

[[[[self childNodeWithName:@"bar1"] childNodeWithName:@"bar1-playPauseButton"] 
  childNodeWithName:@"bar1-playPauseButtonLabel"] setText:@"somethingElse"];

and I get an error:

No visible @interface for 'SKNode' declares the selector 'setText:'

I also tried creating a local SKNode, passing the childNode reference to it and the trying to set the text with dot notion like thisLabelNode.text=@"somethingElse" and while this doesn't cause an error, it also does not change the text.

Any ideas?

thanks, rich

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
user2887097
  • 309
  • 4
  • 12

1 Answers1

1

childNodeWithName returns an object of type SKNode*, not SKLabelNode. Hence the error.

If you know that the returned node is a SKLabelNode (or nil) you can cast it. I would also recommend to avoid nesting too many function calls as that'll make your code harder to read. Plus you can use the search feature to your advantage here:

id label = [self childNodeWithName:@"//bar1-playPauseButtonLabel"];
((SKLabelNode*)label).text = @"whatever";

The // prefix indicates that you want to search the node graph starting with self recursively. This will return the first node found that matches the given name.

CodeSmile
  • 64,284
  • 20
  • 132
  • 217