#pragma once
#include "cocos2d.h"
using namespace cocos2d;
#include "ui/CocosGUI.h"
using namespace ui;
class TextFieldDemo :public Scene
{
public:
virtual bool init();
CREATE_FUNC(TextFieldDemo);
static Scene* createScene();
char* FontToUTF8(const char* font);
private:
TextField* id; //id文本框
TextField* key; //keyword文本框
Button* go; //登录按钮
};
以下是cpp文件
#include "TextFieldDemo.h"
#include "loding.h"
Scene* TextFieldDemo::createScene()
{
return TextFieldDemo::create();
}
bool TextFieldDemo::init()
{
if (!Scene::init())
{
return false;
}
//按钮创建
go = Button::create("112.png", "113.png", "114.png");
this->addChild(go);
//权限默认为不能按
go->setEnabled(false);
//登陆背景
auto put_in = Sprite::create("denglu.png");
put_in->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
put_in->setPosition(Director::getInstance()->getVisibleSize()/2);
this->addChild(put_in);
//账号文本框初始化
id = TextField::create();
//设置账号文本框字体
id->setFontName("arial");
//设置文本框大小
id->setFontSize(36);
//设置账号文本框默认显示
auto _id = String::create(TextFieldDemo::FontToUTF8("请输入您的账号"));
id->setPlaceHolder(_id->getCString());
//设置显示颜色
id->setColor(Color3B::RED);
this->addChild(id);
//设置账号文本框坐标
id->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
id->setPosition(put_in->getPosition()+Vec2(30,-50));
//设置密码文本框
key = TextField::create();
key->setFontName("arial");
key->setFontSize(36);
auto _key = String::create(TextFieldDemo::FontToUTF8("请输入您的密码"));
key->setPlaceHolder(_key->getCString());
key->setColor(Color3B::RED);
this->addChild(key);
key->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
key->setPosition(put_in->getPosition() + Vec2(30, -160));
//设置按钮的权限根据账号密码改动
key->addEventListener([&](Ref* ref, ui::TextField::EventType type)
{
//类型转换
auto temp = dynamic_cast<TextField*>(ref);
//初始化设定为账号和密码大于8位才能使用go按钮进行登录
if (temp->getStringLength() > 8 && id->getStringLength() > 8)
{
go->setEnabled(true);
}
else //如果少了就设置为不可按
{
go->setEnabled(false);
}
});
//设置按钮事件
go->addTouchEventListener([&](Ref* ref, ui::Button::TouchEventType type)
{
if (type == Button::TouchEventType::ENDED)
{
Director::getInstance()->replaceScene(loding::createScene());
}
});
go->setAnchorPoint(Vec2::ANCHOR_MIDDLE_TOP);
go->setPosition(key->getPosition() + Vec2(0, -100));
return true;
}
//转cocos可识别中文
char* TextFieldDemo::FontToUTF8(const char* font) {
int len = MultiByteToWideChar(CP_ACP, 0, font, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len + 1];
memset(wstr, 0, len + 1);
MultiByteToWideChar(CP_ACP, 0, font, -1, wstr, len);
len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
char* str = new char[len + 1];
memset(str, 0, len + 1);
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
if (wstr)delete[] wstr;
return str;
}