---
title: "CCMenuItemSprite 如何更改sprite 图片"
author: "mmdev"
date: "2012-12-01T01:45:00Z"
tags: []
slug: "ccmenuitemsprite-sprite"
draft: false
lastmod: "2013-01-05T09:48:42Z"
id: 1761010
url: "https://mmdev.iteye.com/blog/1761010"
---

============================================================

博文原创，转载请声明出处

[蓝岩--移动互联网老兵](http://blog.csdn.net/shencaifeixia1)

============================================================

在cocos2d的游戏设置见面中，要添加控制声音开关的按钮，我的button使用CCMenuItemSprite来时显得，当开启声音时候，显示A图片，关闭时候显示B图片，这就需要修改CCMenuItemSprite的图片，方法如下：

在创建menu的时候，这只一种图片

```
     CCSprite* audion= [CCSprite spriteWithSpriteFrameName:@"button_audio.png"];
     CCSprite*audios= [CCSprite spriteWithSpriteFrameName:@"button_audio.png"];

    CCMenuItemSprite* audiosa=[CCMenuItemSprite itemFromNormalSprite:audion selectedSprite:audios target:self selector:@selector(audio:)];
```

\-----

注意，在创建CCMenuItemSprite的时候，必须创建你两个CCSprite，否则会出现一下错误：

```
 Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'child already added. It can't be added again'
```

\----

点击按钮，会触发 audio:函数，此函数定义如下：

```
-(void)audio:(id)sender{
    NSLog(@"send:%@",sender);
    CCMenuItemSprite* i=(CCMenuItemSprite*)sender;

    CCSprite* audion= [CCSprite spriteWithSpriteFrameName:@"button_audio_bar.png"];
    CCSprite* audios= [CCSprite spriteWithSpriteFrameName:@"button_audio_bar.png"];
    i.normalImage = audion;
    i.selectedImage=audios;
}
```

这里我们拿到的sender是CCMenuItemSprite，转换后可以设置其normalImage，selectedImage来实现图片的修改。

其实normalImage并不是严格意义上的图片，而是 CCNode&lt;CCRGBAProtocol&gt;的子类，所以我们可以将其设置为CCSprite。