1.EditBox
EditBox即cocos2dx提供的输入框组件,创建需要一个九宫格精灵图片和Size作为初始化参数,我自己使用发现有一个小问题,就是当我点击组件进行输入时,不是使用图片背景,而是普通的组件背景,这样就显得有失美感。不知道是不是自己没设置对。
2.ControlSlider
即滑动条,一般用作音量调节等。
3.代码实现
说了这么多下面看下具体的代码实现:
#ifndef _EDIT_TEST_H_
#define _EDIT_TEST_H_
#include"cocos2d.h"
#include"cocos-ext.h"
USING_NS_CC_EXT;
USING_NS_CC;
class EditTest:public Layer,public EditBoxDelegate
{
public:
virtual bool init()override;
static Scene* createScene();
//EditBoxDelegate的纯虚函数,子类必须实现
void editBoxReturn(EditBox* editbox) {};
//文本改变事件
virtual void editBoxTextChanged(EditBox* editbox, const std::string& text);
void sliderCallback(Ref* pSender,Control::EventType controlEvent);
CREATE_FUNC(EditTest);
};
#endif // !_EDIT_TEST_H_
#include "EditTest.h"
bool EditTest::init()
{
if (!Layer::init())
{
return false;
}
//
const auto size = Director::getInstance()->getWinSize();
//
const auto layer = LayerColor::create(Color4B::WHITE);
this->addChild(layer);
//
const auto bg =Scale9Sprite::create("0.png");
//
const auto editBox = EditBox::create(Size(263,32),bg,bg);
editBox->setPosition(size/2);
editBox->setFontColor(Color3B::RED);
editBox->setInputMode(EditBox::InputMode::DECIMAL);
editBox->setInputMode(EditBox::InputMode::SINGLE_LINE);
editBox->setBright(false);
editBox->setText("0");
editBox->setDelegate(this);
editBox->setTag(10);
this->addChild(editBox);
//
const auto slide_control = ControlSlider::create("0.png","3.png","CloseSelected.png");
slide_control->setPosition(Vec2(size.width/2,size.height/3));
slide_control->setMinimumValue(0);
slide_control->setMaximumValue(100);
slide_control->setValue(0);
slide_control->setTag(20);
slide_control->addTargetWithActionForControlEvents(this,cccontrol_selector(EditTest::sliderCallback),Control::EventType::VALUE_CHANGED);
this->addChild(slide_control);
return true;
}
Scene* EditTest::createScene()
{
auto scene = Scene::create();
auto layer = EditTest::create();
scene->addChild(layer);
return scene;
}
void EditTest::editBoxTextChanged(EditBox* editbox, const std::string& text)
{
auto value =std::atoi(text.c_str());
if (value > 100)
{
value = 100;
}
dynamic_cast<ControlSlider*>(this->getChildByTag(20))->setValue(value);
}
void EditTest::sliderCallback(Ref* pSender, Control::EventType controlEvent)
{
int value = dynamic_cast<ControlSlider*>(pSender)->getValue();
char buffer[10];
sprintf(buffer, "%d", value);
dynamic_cast<EditBox*>(this->getChildByTag(10))->setText(buffer);
}
4.效果
参考:https://blog.csdn.net/chinahaerbin/article/details/28025717