cocos2dx開發 之 使用TextField文本框登錄頁面的初步開發(代碼內註釋詳細)

#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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章