昨天说了一下CCEditBox,今天来说另一个输入框的类CCTextFieldTTF,这个类是继承自CCLabelTTF,是动态改变的CCLabelTTF,使用起来比CCEditBox要麻烦的多。这里说一下原理,具体在实际的开发中,还要进行一些其他的设置。

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"

using namespace cocos2d;
//需要继承自CCTextFieldDelegate
class HelloWorld : public cocos2d::CCLayer , public CCTextFieldDelegate
{
public:
    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    virtual bool init();

    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::CCScene* scene();

    // implement the "static node()" method manually
    CREATE_FUNC(HelloWorld);

	//需要实现以下的函数
	//当用户启动虚拟键盘的时候的回调函数
	virtual bool onTextFieldAttachWithIME(CCTextFieldTTF * mysender);
	//当用户关闭虚拟键盘的时候的回调函数
	virtual bool onTextFieldDetachWithIME(CCTextFieldTTF * mysender);
	//当用户输入的时候的回调函数
	virtual bool onTextFieldInsertText(CCTextFieldTTF * mysender,const char * text,int textnum);
	//当用户删除文字的时候的回调函数
	virtual bool onTextFieldDeleteBackward(CCTextFieldTTF * mysender,const char * text,int textnum);
};

#endif // __HELLOWORLD_SCENE_H__
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }

    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
	//CCTextFieldTTF继承自CCLabelTTF,create方法是CCLabelTTF的方法,这里不能用
	CCTextFieldTTF * textField = CCTextFieldTTF::textFieldWithPlaceHolder("please input","",24);
	textField->setPosition(ccp(visibleSize.width/2,visibleSize.height/2));
	//设置代理,这样的话会执行传入参数的那几个虚函数
	textField->setDelegate(this);
	//attachWithIME()开启输入
	textField->attachWithIME();
	//detachWithIME()关闭输入
	//textField->detachWithIME();
	this->addChild(textField);

    return true;
}

//以下四个函数的返回类型都是bool型,返回true代表中断操作,就是不开启键盘,不移除键盘,不输入文字,不删除文字
//所以我们一般都是返回的false
bool HelloWorld::onTextFieldAttachWithIME(CCTextFieldTTF * sender)
{
	CCLog("attach with ime");
	return false;
}

bool HelloWorld::onTextFieldDetachWithIME(CCTextFieldTTF * sender)
{
	CCLog("detach with ime");
	return false;
}

bool HelloWorld::onTextFieldInsertText(CCTextFieldTTF * sender,const char * text,int textnum)
{
	CCLog("%s+%d",text,textnum);
	return false;
}

bool HelloWorld::onTextFieldDeleteBackward(CCTextFieldTTF * sender,const char * text,int textnum)
{
	CCLog("%s+%d",text,textnum);
	return false;
}