Search code examples
iossprite-kitsklabelnode

How to change text of a SKLabelNode?


How do I update a label's text that was created in initWithSize? Here is the code for the label within the initWithSize:

SKLabelNode *scoreLabel = [SKLabelNode labelNodeWithFontNamed:@"TimesNewRoman"];
    scoreLabel.text = [NSString stringWithFormat:@"%i", score];
    scoreLabel.fontSize = 30;
    scoreLabel.position = CGPointMake(290, CGRectGetMidY(self.frame) - 30);
    scoreLabel.zRotation = -M_PI/2;
    [self addChild:scoreLabel];

As the game is running I update the variable score and I was just wondering how I can get the label to display the new score.


Solution

  • You will have to declare scoreLabel in the header file and then just so scoreLabel.text = //Your text anywhere you want.

    EDIT:

    In your .h file, declare @property (nonatomic,strong) SKLabelNode *scoreLabel;

    In your .m file, add @synthesize scoreLabel;

    When you are initializing the label do

    self.scoreLabel = [SKLabelNode labelNodeWithFontNamed:@"TimesNewRoman"];

    and not

    SKLabelNode *scoreLabel = [SKLabelNode labelNodeWithFontNamed:@"TimesNewRoman"];