SwitchControl的用法
SwitchControl控件类似于现实生活中的开关,起到开关的作用。由于该控件相对简单,下面将直接通过代码示例详细介绍其用法。
准备工作
首先,需要在工程目录下的Resource文件夹中添加三张图片,分别为 switch-mask.png、switch-on.png 和 switch-off.png,以及 switch-thumb.png。
代码实现
1. 头文件 SwitchControl.h
在 SwitchControl.h 文件中添加以下代码:
#ifndef _SwitchControl_H_
#define _SwitchControl_H_
#include "cocos2d.h"
#include "cocos-ext.h"
USING_NS_CC;
USING_NS_CC_EXT;
class SwitchControl : public CCLayer {
public:
static CCScene* scene();
CREATE_FUNC(SwitchControl);
bool init();
void switchValueChanged(CCObject*, CCControlEvent);
};
#endif
上述代码定义了 SwitchControl 类,继承自 CCLayer,并声明了 scene 静态函数用于创建场景,init 函数用于初始化,switchValueChanged 函数用于处理开关状态改变的事件。
2. 源文件 SwitchControl.cpp
在 SwitchControl.cpp 文件中添加以下代码:
#include "SwitchControl.h"
CCScene* SwitchControl::scene() {
CCScene* s = CCScene::create();
SwitchControl* layer = SwitchControl::create();
s->addChild(layer);
return s;
}
bool SwitchControl::init() {
CCLayer::init();
// 获取窗口的大小
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
// 设置ControlSwitch控件打开时显示的文字“ON”
CCLabelTTF* on = CCLabelTTF::create("ON", "Arial", 16);
// 设置ControlSwitch控件关闭时显示的文字“OFF”
CCLabelTTF* off = CCLabelTTF::create("OFF", "Arial", 16);
// 设置ControlSwitch控件打开时文字的颜色
on->setColor(ccc3(0, 0, 0));
// 设置ControlSwitch控件关闭时文字的颜色
off->setColor(ccc3(0, 0, 0));
// 创建ControlSwitch控件
CCControlSwitch* control = CCControlSwitch::create(
CCSprite::create("switch-mask.png"),
CCSprite::create("switch-on.png"),
CCSprite::create("switch-off.png"),
CCSprite::create("switch-thumb.png"),
on,
off
);
// 将ControlSwitch控件添加到当前层
addChild(control);
// 设置ControlSwitch控件的位置,使其位于窗口中心
control->setPosition(ccp(winSize.width / 2, winSize.height / 2));
// 注册valuechange消息,当开关状态改变时,调用switchValueChanged函数
control->addTargetWithActionForControlEvents(
this,
cccontrol_selector(SwitchControl::switchValueChanged),
CCControlEventValueChanged
);
return true;
}
void SwitchControl::switchValueChanged(CCObject* sender, CCControlEvent ev) {
if (ev == CCControlEventValueChanged) {
CCControlSwitch* control = (CCControlSwitch*)sender;
if (control->isOn()) {
CCLog("Switch is ON");
} else {
CCLog("Switch is Off");
}
} else {
CCLog("other events");
}
}
在 scene 函数中,创建了一个新的场景,并将 SwitchControl 层添加到该场景中。init 函数完成了 ControlSwitch 控件的初始化工作,包括设置显示文字、颜色、创建控件、设置位置以及注册事件处理函数。switchValueChanged 函数根据开关的状态输出相应的日志信息。
通过以上步骤,就可以在项目中使用 SwitchControl 控件实现开关功能,并处理开关状态改变的事件。