Creating a button using CCMenuItemToggle in cocos2d


Last time we talked about creating a simple menu in cocos2d. This tutorial will show you how to use CCMenuItemToggle to create a simple sound on/off button using images to represent the two states.

Create a new cocos2d application, or use the application from the last tutorial. We’ll need to use some images for the on/off states, so add the following images to your project’s Resources group:

In the scene where you would like to place your sound on/off button, add the following code to your init method:

// Sound on/off toggle
CCMenuItem *soundOnItem = [CCMenuItemImage itemFromNormalImage:@"soundOn.png"

CCMenuItem *soundOffItem = [CCMenuItemImage itemFromNormalImage:@"soundOff.png"

CCMenuItemToggle *soundToggleItem = [CCMenuItemToggle itemWithTarget:self
							       items:soundOnItem, soundOffItem, nil];

First, we create two menu items from our sound on/off images. They’ll just be used as reference for our toggle item, so we just set our target and selector to nil.

Next, we create the actual CCMenuItemToggle. The target will be self, and we’ll specify a soundButtonTapped: method for our selector (which we’ll create later). Then, we add our soundOnItem and soundOffItem to the toggle.

Now, we’ll create a menu to add our soundToggleItem:

CCMenu *bottomMenu = [CCMenu menuWithItems:soundToggleItem, nil];
soundToggleItem.position = ccp( -90,-120);
[self addChild: bottomMenu z: 10];

Finally, let’s just add our method for when the sound button is tapped:

-(void) soundButtonTapped: (id) sender
 	// do something… maybe even turn the sound on/off!
	NSLog(@"Sound button tapped!");

Build and run, and you should see a sound on/off button that changes state each time you tap it.

Stephen Ceresia

Stephen Ceresia is Marketing Manager at ReignDesign. Stephen is from Canada and is currently based in Shanghai.


  1. A small mistake(for recent cocos2d at least): Replace soundToggleItem.position with bottomMenu.position.

    For newer cocos2d version, the coordinates also work differently.

  2. thxs for the tut, but lets say if I will create this kind of sound on/off toggle item in different scene (lets say in mainmenu.m and gamelayer.m), and I toggled mute in mainmenu.m, but when I went to gamelayer.m, since it will create another new sound toggle item in it, it will be displayed as SoundOn not mute right? how can I make it work between different scenes (.m file)? thxs again

  3. thanks for this tutorial!! helped me a lot!
    just one small workaround: itemFromNormalImage is deprecated in current version -> use itemWithNormalImage instead.

Leave a Reply

Your email address will not be published. Required fields are marked *

Share this post