在test项目中的ControlExtensionText CCControlSwitchTest目录下面的CCControlSwitchTest.cpp中,通过这个例子,我们也可以制作出不错的开关效果,以下是我尝试的代码:
首先声明文件:
#ifndef __loading__LoadingScene__ #define __loading__LoadingScene__ #include <iostream> #include "cocos2d.h" #include "cocos-ext.h" USING_NS_CC_EXT; class LoadingScene :public CCControlSwitch //注意继承的类 { public: bool init(); CREATE_FUNC(LoadingScene); static cocos2d::CCScene *scene(); void valueChanged(CCObject* sender, CCControlEvent controlEvent); cocos2d::CCLabelTTF *ttf; }; #endif /* defined(__loading__LoadingScene__) */
类的实现文件:
#include "LoadingScene.h" #include "cocos-ext.h" USING_NS_CC_EXT; USING_NS_CC; bool LoadingScene::init() { if (!CCControlSwitch::init()) //原示例中为CCControlScene::init(),但我写后一直不识别,不知道什么原因,估计是我继承的类不同吧 { return false; } CCSprite *bg=CCSprite::create("fullbg.png"); this->addChild(bg); CCSize size=CCDirector::sharedDirector()->getWinSize(); CCControlSwitch *switch1=CCControlSwitch::create( CCSprite::create("switch-mask.png"), //背景图片 CCSprite::create("switch-on.png"), //开状态背景图片 CCSprite::create("switch-off.png"), //关状态背景图片 CCSprite::create("switch-thumb.png"), //开关背景图片 CCLabelTTF::create("On", "Arial-BoldMT", 16), //开文字标签 CCLabelTTF::create("Off", "Arial-BoldMT", 16) //关文字标签 ); this->addChild(switch1,1); this->setPosition(ccp(size.width/2, size.height/2)); //添加动作事件 switch1->addTargetWithActionForControlEvents(this, cccontrol_selector(LoadingScene::valueChanged), CCControlEventValueChanged); CCScale9Sprite *sp=CCScale9Sprite::create("buttonBackground.png"); //添加九妹图片 sp->setContentSize(CCSizeMake(200, 300)); //设置九妹图片大小 this->addChild(sp,1); sp->setAnchorPoint(ccp(1,1.3)); sp->setPosition(ccp(size.width/3, size.height/3)); ttf=CCLabelTTF::create("On", "Arial-BoldMT", 22); ttf->setPosition(ccp(sp->getContentSize().width/2, sp->getContentSize().height/2)); sp->addChild(ttf,1); //在九妹图片上添加文字标签 return true; } CCScene *LoadingScene::scene() { CCScene *scene=CCScene::create(); LoadingScene *layer=LoadingScene::create(); scene->addChild(layer); return scene; } void LoadingScene::valueChanged(CCObject* sender, CCControlEvent controlEvent) { CCControlSwitch* pSwitch = (CCControlSwitch*)sender; if (pSwitch->isOn()) //判断标签是否是on状态 { ttf->setString("On"); } else { ttf->setString("Off"); } }
最后,实现的效果如下: