头文件要包含:
#include "cocos-ext.h" USING_NS_CC_EXT;
类要继承于
class HelloWorld : public cocos2d::Layer,public EditBoxDelegate
这里有个问题,我这样写之后会报错,提示:EditBoxDeletgate不是类名或者结构名,这个纠结了很久,后来在网上看到别人用scoreView的时候也会出现这样的问题,有人说包含目录:$(EngineRoot)就行了,我试了一下果然成功~
在类里重载编辑框的函数
//---------------------------------添加编辑框 virtual void editBoxEditingDidBegin(cocos2d::extension::EditBox* editBox); virtual void editBoxEditingDidEnd(cocos2d::extension::EditBox* editBox); virtual void editBoxTextChanged(cocos2d::extension::EditBox* editBox,const std::string &text); virtual void editBoxReturn(cocos2d::extension::EditBox *editBox);
根据函数名我们可以知道这些函数的作用
在init函数里创建编辑框
//---------------------------------添加账号框 auto pEditBox_name = EditBox::create(CCSizeMake(250,50),Scale9Sprite::create("button.png")); pEditBox_name->setPosition(ccp(visibleSize.width/2,visibleSize.height*3/4)); pEditBox_name->setFontColor(Color3B(0,0));//设置字体颜色 pEditBox_name->setPlaceHolder("Name:");//设置预置文本 pEditBox_name->setMaxLength(8);//设置最大长度 pEditBox_name->setInputMode(cocos2d::ui::EditBox::InputMode::SINGLE_LINE);//可以输入任何,但是不包括换行 pEditBox_name->setInputFlag(cocos2d::ui::EditBox::InputFlag::INITIAL_CAPS_WORD);//设置输入标志位 pEditBox_name->setReturnType(cocos2d::ui::EditBox::KeyboardReturnType::DONE);//设置返回类型 pEditBox_name->setDelegate(this);//当前类继承CCEditBoxDelegate类 pEditBox_name->setTag(101); this->addChild(pEditBox_name); //---------------------------------添加密码框 auto pEditBox_password = EditBox::create(CCSizeMake(250,Scale9Sprite::create("button.png")); pEditBox_password->setPosition(ccp(visibleSize.width/2,visibleSize.height*2/4)); pEditBox_password->setFontColor(Color3B(0,0)); pEditBox_password->setPlaceHolder("Password:"); pEditBox_password->setMaxLength(6); pEditBox_password->setInputMode(cocos2d::ui::EditBox::InputMode::NUMERIC); pEditBox_password->setInputFlag(cocos2d::ui::EditBox::InputFlag::PASSWORD); pEditBox_password->setReturnType(cocos2d::ui::EditBox::KeyboardReturnType::DONE); pEditBox_password->setDelegate(this); pEditBox_password->setTag(102); this->addChild(pEditBox_password);
然后重写编辑框的功能函数
void HelloWorld::editBoxEditingDidBegin(EditBox *editBox) { CCLOG("start edit"); } void HelloWorld::editBoxEditingDidEnd(EditBox *editBox) { CCLOG("end edit"); } void HelloWorld::editBoxReturn(EditBox *editBox) { CCLOG("editBox return"); } void HelloWorld::editBoxTextChanged(EditBox *editBox,const std::string &text) { auto editBox = (EditBox*)editBox; switch(editBox->getTag()) { case 101: CCLOG("EditBox_name changed"); m_name=text; break; case 102: CCLOG("EditBox_password changed"); m_password=text; break; default: break; } }
好了,这样编辑框就出来了
之后说说如何做个登陆的效果
原文链接:https://www.f2er.com/cocos2dx/342513.html