今天, 我们来学习CCControl中的另一个控件, CCControlSwitch控件, 这个控件在手机上可是很常见的, 什么WiFi的打开关闭之类的, 都是用的这个, 废话少说, 我们还是来看看如何创建一个CCControlSwitch控件吧,
用法:
CCControlSwitch::create( 底图精灵对象, 开精灵对象, 关精灵对象, 按钮精灵对象, 打开时显示的文字, 关闭时打开的文字);
找四张图片, 我这里没有现成的, 所以找了度娘一下下
抠出我们要用的四张图片作为精灵对象:
创建一个CCControlSwitch:
在写之前, 我还得唠叨一句, CCControlSwitch属于扩展库的哦, 所以#include "cocos-ext.h"/USING_NS_CC_EXT;是不能缺少的哦
CCControlSwitch* cs = CCControlSwitch::create( //创建一个CCControlSwitch
CCSprite::create( "bg.png"),
CCSprite::create( "on.png"),
CCSprite::create( "off.png"),
CCSprite::create( "bt.png"));
cs->setPosition( ccp( visibleSize.width / 2, visibleSize.height / 2 + 100));
cs->setEnabled( true); //设置可用
cs->setOn( false); //设置开还是关
addChild( cs);
效果:
点一下:
我们来添加回调函数:
void callMySwitch( CCObject* pSender, CCControlEvent controlEvent);
再创建一个标签, 顺便把事件绑定了:
CCLabelTTF* ttf = CCLabelTTF::create( "none", "Arial", 24);
ttf->setPosition( ccp( visibleSize.width / 2, visibleSize.height / 2));
addChild( ttf, 0, 102);
cs->addTargetWithActionForControlEvents(this,
cccontrol_selector(HelloWorld::callMySwitch),
CCControlEventValueChanged);
然后我们实现, 回调函数:
void HelloWorld::callMySwitch( CCObject* pSender, CCControlEvent controlEvent)
{
CCControlSwitch* cs = (CCControlSwitch*)this->getChildByTag( 101);
CCLabelTTF* ttf = (CCLabelTTF*)this->getChildByTag( 102);
if ( cs->isOn())
{
ttf->setString( "on");
}
else
{
ttf->setString( "off");
}
}
看看效果:
成功的完成了事件的响应,
额, 今天就到这里为止了, 明天我们来学习CCControl的最后一个控件, 进度条