您好,欢迎访问一九零五行业门户网

cocos2dx中的输入类CCTextFieldTTF的用法

cocos2dx中的输入类cctextfieldttf。还是相当好用的, 其中,很多人都会关注怎么判断用户输入的数字,字母,汉字? 通过重载ontextfieldinserttext函数,我们可以自定义自己想要的效果。 以下代码,是参考官方的示例,添加了是否数字、字母、汉字的判断,还
cocos2dx中的输入类cctextfieldttf。还是相当好用的,
其中,很多人都会关注怎么判断用户输入的数字,字母,汉字?
通过重载ontextfieldinserttext函数,我们可以自定义自己想要的效果。
以下代码,是参考官方的示例,添加了是否数字、字母、汉字的判断,还增加了以空格和回车作为输入结束符。
以下代码,拷到新建项目的helloworld中可以直接用(本文版本cocos2dx 2.2.2)。
上代码: .h文件
#ifndef __helloworld_scene_h__#define __helloworld_scene_h__#include cocos2d.husing_ns_cc;class helloworld : public cocos2d::cclayer,public cctextfielddelegate,public ccimedelegate{public: // method 'init' in cocos2d-x returns bool, instead of 'id' in cocos2d-iphone (an object pointer) virtual bool init(); // there's no 'id' in cpp, so we recommend to return the class instance pointer static cocos2d::ccscene* scene(); // preprocessor macro for static create() constructor ( node() deprecated ) create_func(helloworld); void callbackremovenodewhendidaction(ccnode * pnode); virtual void onclicktracknode(bool bclicked,cctextfieldttf * psender); // cclayer virtual void onenter(); virtual void onexit(); virtual void registerwithtouchdispatcher(); virtual bool cctouchbegan(cctouch *ptouch, ccevent *pevent); virtual void cctouchended(cctouch *ptouch, ccevent *pevent); // cctextfielddelegate virtual bool ontextfieldattachwithime(cctextfieldttf * psender); virtual bool ontextfielddetachwithime(cctextfieldttf * psender); virtual bool ontextfieldinserttext(cctextfieldttf * psender, const char * text, int nlen); virtual bool ontextfielddeletebackward(cctextfieldttf * psender, const char * deltext, int nlen); virtual bool ondraw(cctextfieldttf * psender); //ccimedelegate //keyboard show/hide notification //virtual void keyboardwillshow(ccimekeyboardnotificationinfo& info); //virtual void keyboardwillhide(ccimekeyboardnotificationinfo& info); private: cctextfieldttf* m_ptextfield; cctextfieldttf* m_ptextfield2; ccaction* m_ptextfieldaction; bool m_baction; int m_ncharlimit; // the textfield max char limit ccpoint m_beginpos; float adjustvert;};#endif // __helloworld_scene_h__
.cpp文件
#include helloworldscene.h#include simpleaudioengine.husing namespace cocos2d;using namespace cocosdenshion;#define font_name thonburi#define font_size 36ccscene* helloworld::scene(){ // 'scene' is an autorelease object ccscene *scene = ccscene::create(); // 'layer' is an autorelease object helloworld *layer = helloworld::create(); // add layer as a child to scene scene->addchild(layer); // return the scene return scene;}// on init you need to initialize your instancebool helloworld::init(){ ////////////////////////////// // 1. super init first if ( !cclayer::init() ) { return false; } settouchenabled(true); //注意要设置当前layer为可触摸 ccsize size = ccdirector::shareddirector()->getwinsize(); ccsprite* psprite = ccsprite::create(helloworld.png); psprite->setposition( ccp(size.width/2, size.height/2) ); this->addchild(psprite, 0); return true;}void helloworld::registerwithtouchdispatcher(){ ccdirector::shareddirector()->gettouchdispatcher()->addtargeteddelegate(this, 0, false);//true会吞噬}void helloworld::onenter(){ cclayer::onenter(); //这个父类的调用很重要! m_ncharlimit = 12; m_ptextfieldaction = ccrepeatforever::create( ccsequence::create( ccfadeout::create(0.25), ccfadein::create(0.25), null )); m_ptextfieldaction->retain(); //这里一定要retain一次,否则会出现内存问题。 m_baction = false; // add cctextfieldttf ccsize s = ccdirector::shareddirector()->getwinsize(); m_ptextfield = cctextfieldttf::textfieldwithplaceholder(, font_name, font_size); m_ptextfield->setcolor(ccwhite); //设置输入编辑框中字符的颜色// m_ptextfield->setsecuretextentry(true); //输入密码时,用点字符替代 m_ptextfield->setdelegate(this); //很重要 勿漏!!! m_ptextfield->setposition(ccp(s.width / 2, s.height / 2+30)); //将输入编辑框的y轴位置设低是为了测试,当出现键盘的时候,输入编辑框的自动向上调整。 addchild(m_ptextfield); m_ptextfield2 = cctextfieldttf::textfieldwithplaceholder(, font_name, font_size); m_ptextfield2->setcolor(ccwhite); //设置输入编辑框中字符的颜色// m_ptextfield2->setsecuretextentry(true); //输入密码时,用点字符替代 m_ptextfield2->setdelegate(this); m_ptextfield2->setposition(ccp(s.width / 2, s.height / 2-30)); //将输入编辑框的y轴位置设低是为了测试,当出现键盘的时候,输入编辑框的自动向上调整。 addchild(m_ptextfield2);}//返回节点的rectstatic ccrect getrect(ccnode * pnode){ ccrect rc; rc.origin = pnode->getposition(); rc.size = pnode->getcontentsize(); rc.origin.x -= rc.size.width / 2; rc.origin.y -= rc.size.height / 2; return rc;}bool helloworld::cctouchbegan(cctouch *ptouch, ccevent *pevent){ cclog(++++++++++++++++++++++++++++++++++++++++++++); m_beginpos = ptouch->getlocation(); return true;}void helloworld::cctouchended(cctouch *ptouch, ccevent *pevent){ if (! m_ptextfield) { return; } ccpoint endpos = ptouch->getlocation(); // 以下这部分代码是用于检测 begin touch 到 end touch之间的距离是否超过5.0,如果是,则返回;否则,继续执行下面的判断是否点击到编辑框的代码。 float delta = 5.0f; if (::abs(endpos.x - m_beginpos.x) > delta || ::abs(endpos.y - m_beginpos.y) > delta) { // not click m_beginpos.x = m_beginpos.y = -1; return; } // decide the tracknode is clicked. ccrect rect; rect = getrect(m_ptextfield); this->onclicktracknode(rect.containspoint(endpos),m_ptextfield); ccrect rect2; rect2 = getrect(m_ptextfield2); this->onclicktracknode(rect2.containspoint(endpos),m_ptextfield2); cclog(----------------------------------);}void helloworld::onclicktracknode(bool bclicked,cctextfieldttf * psender){ if (bclicked) { // textfieldttftest be clicked cclog(attachwithime); psender->attachwithime(); //调用键盘 } else { // textfieldttftest not be clicked cclog(detachwithime); psender->detachwithime(); //隐藏键盘 }}void helloworld::onexit(){ m_ptextfieldaction->release(); ccdirector::shareddirector()->gettouchdispatcher()->removedelegate(this);}// cctextfielddelegate protocolbool helloworld::ontextfieldattachwithime(cctextfieldttf * psender){ if (! m_baction) { psender->runaction(m_ptextfieldaction); m_baction = true; } return false;}bool helloworld::ontextfielddetachwithime(cctextfieldttf * psender){ if (m_baction) { psender->stopaction(m_ptextfieldaction); psender->setopacity(255); m_baction = false; } return false;}//本文的重点在此bool helloworld::ontextfieldinserttext(cctextfieldttf * psender, const char * text, int nlen){ //if insert enter, treat as default to detach with ime cclog(%d,nlen);//当前输入的单个字符长度 //空格和\n作为输入结束符 if (*text==' '||'\n' == *text) { psender->detachwithime(); //关闭输入 隐藏键盘 return true; } //中文的nlen是3 数字和字母的是1 //如果输入是中文 则不接受输入的内容 if (nlen>1) { return true;//true 则不接受输入的内容 但是可以继续输入 } //判断是否数字或者字符,和下划线_ //不接受数字和英文大小写字符以外的输入 if((*text>='0'&& *text='a'&&*text='a')&&(*text='_') { } else { return true; } // if the textfield's char count more than m_ncharlimit, doesn't insert text anymore. if (psender->getcharcount() >= m_ncharlimit) { return true; } //// 创建输入时动画 create a insert text sprite and do some action //cclabelttf * label = cclabelttf::create(text, font_name, font_size); //this->addchild(label); //cccolor3b color = { 226, 121, 7}; //label->setcolor(color); // //// move the sprite from top to position //ccpoint endpos = psender->getposition(); //if (psender->getcharcount()) //{ // endpos.x += psender->getcontentsize().width / 2; //} //ccsize inputtextsize = label->getcontentsize(); //ccpoint beginpos(endpos.x, ccdirector::shareddirector()->getwinsize().height - inputtextsize.height * 2); // //float duration = 0.5; //label->setposition(beginpos); //label->setscale(8); // //ccaction * seq = ccsequence::create( // ccspawn::create( // ccmoveto::create(duration, endpos), // ccscaleto::create(duration, 1), // ccfadeout::create(duration), // 0), // cccallfuncn::create(this, callfuncn_selector(helloworld::callbackremovenodewhendidaction)), // 0); //label->runaction(seq); return false;}bool helloworld::ontextfielddeletebackward(cctextfieldttf * psender, const char * deltext, int nlen){ ////创建删除字符动画 create a delete text sprite and do some action //cclabelttf * label = cclabelttf::create(deltext, font_name, font_size); //this->addchild(label); // //// move the sprite to fly out //ccpoint beginpos = psender->getposition(); //ccsize textfieldsize = psender->getcontentsize(); //ccsize labelsize = label->getcontentsize(); //beginpos.x += (textfieldsize.width - labelsize.width) / 2.0f; // //ccsize winsize = ccdirector::shareddirector()->getwinsize(); //ccpoint endpos(- winsize.width / 4.0f, winsize.height * (0.5 + (float)rand() / (2.0f * rand_max))); // //float duration = 1; //float rotateduration = 0.2f; //int repeattime = 5; //label->setposition(beginpos); // //ccaction * seq = ccsequence::create( // ccspawn::create( // ccmoveto::create(duration, endpos), // ccrepeat::create( // ccrotateby::create(rotateduration, (rand()%2) ? 360 : -360), // repeattime), // ccfadeout::create(duration), // 0), // cccallfuncn::create(this, callfuncn_selector(helloworld::callbackremovenodewhendidaction)), // 0); //label->runaction(seq); return false;}bool helloworld::ondraw(cctextfieldttf * psender){ return false;}void helloworld::callbackremovenodewhendidaction(ccnode * pnode){ this->removechild(pnode, true);}//虚拟键盘//void helloworld::keyboardwillshow(ccimekeyboardnotificationinfo& info)//{// cclog(textinputtest:keyboardwillshowat(origin:%f,%f, size:%f,%f),// info.end.origin.x, info.end.origin.y, info.end.size.width, info.end.size.height);// // if (! m_ptextfield)// {// return;// }// // ccrect recttracked = getrect(m_ptextfield);// // cclog(textinputtest:trackingnodeat(origin:%f,%f, size:%f,%f),// recttracked.origin.x, recttracked.origin.y, recttracked.size.width, recttracked.size.height);// // // if the keyboard area doesn't intersect with the tracking node area, nothing need to do.// if (! recttracked.intersectsrect(info.end))// {// return;// }// // // assume keyboard at the bottom of screen, calculate the vertical adjustment.// // //计算出需要y轴需要调整的距离// adjustvert = info.end.getmaxy() - recttracked.getminy();// cclog(textinputtest:needadjustverticalposition(%f), adjustvert);// // // move all the children node of keyboardnotificationlayer// ccarray * children = getchildren();// ccnode * node = 0;// int count = children->count();// ccpoint pos;// for (int i = 0; i objectatindex(i);// pos = node->getposition();// pos.y += adjustvert; //所有的节点都向上移动// node->setposition(pos);// }//}//////void helloworld::keyboardwillhide(ccimekeyboardnotificationinfo &info)//{// cclog(textinputtest:keyboardwillshowat(origin:%f,%f, size:%f,%f),// info.end.origin.x, info.end.origin.y, info.end.size.width, info.end.size.height);// // ccarray * children = getchildren();// ccnode * node = 0;// int count = children->count();// ccpoint pos;// for (int i = 0; i objectatindex(i);// pos = node->getposition();// pos.y -= adjustvert; //所有的节点都向下移动,恢复原来的位置// node->setposition(pos);// }//}
(注意:ontextfieldinserttext函数中是const char * text,使用的时候需要星号* text)
输入框,把锚点设置在(0.0,0.5),则会左对齐,此外如果这个修改了,也需要修改触摸的范围。
我习惯另外做一个显示的背景框,用作点击范围,这样用户使用比较方便。
cctextfieldttf相当灵活,方便我们自定义。很好!大赞!
参考资料:
http://blog.csdn.net/crayondeng/article/details/12175367 cocos2d-x cceditbox & cctextfieldttf
其它类似信息

推荐信息