How to change the text on a CCMenuItem

20 Nov

In the cocos2d framework for building games in Objective C, the standard way to build a menu or button is to create a CCMenuItem object.

For example, one might use the code :

[CCMenuItemFont setFontName:@"Marker Felt"];
[CCMenuItemFont setFontSize:35];
CCMenuItem* playGame = [CCMenuItemFont itemFromString:@"Play Game" target:self selector:@selector(playGame:)]];

I was creating some menu items for a game settings screen, and I wanted to change the text of the items. However, there doesn’t seem to be any method of CCMenuItem that does the trick.

The reason for this is simple – a CCMenuItem might not have any text, for example, if the CCMenuItem has an image instead. There might be no meaningful way to change the text.

In the case of a CCMenuItem created from CCMenuItemFont, however, there is text, and it can be changed. That’s because the object that comes out of the code above is not just a CCMenuItem, it’s actually a member of a subclass of CCMenuItem, and has more methods available.

So, if you use the code below :

[CCMenuItemFont setFontName:@”Marker Felt”];
[CCMenuItemFont setFontSize:35];
CCMenuItemFont* playGame = [CCMenuItemFont itemFromString:@”Play Game”┬átarget:self selector:@selector(playGame:)]];

then you can change the text of playGame using the code below :

[playGame setString:@"Game Finished!"];

and that’s how it’s done!



Tags: , , , ,

Leave a Reply