cocos2dx中的输入类CCTextFieldTTF的用法
cocos2dx中的输入类CCTextFieldTTF。还是相当好用的, 其中,很多人都会关注怎么判断用户输入的数字,字母,汉字? 通过重载onTextFieldInsertText函数,我们可以自定义自己想要的效果。 以下代码,是参考官方的示例,添加了是否数字、字母、汉字的判断,还
cocos2dx中的输入类CCTextFieldTTF。还是相当好用的,
其中,很多人都会关注怎么判断用户输入的数字,字母,汉字?
通过重载onTextFieldInsertText函数,我们可以自定义自己想要的效果。
以下代码,是参考官方的示例,添加了是否数字、字母、汉字的判断,还增加了以空格和回车作为输入结束符。
以下代码,拷到新建项目的HelloWorld中可以直接用(本文版本cocos2dx 2.2.2)。
上代码: .h文件
#ifndef __HELLOWORLD_SCENE_H__ #define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" USING_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.h" using namespace cocos2d; using namespace CocosDenshion; #define FONT_NAME "Thonburi" #define FONT_SIZE 36 CCScene* 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 instance bool 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("<click here for input>", 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("<click here for input>", 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); } //返回节点的rect static 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 protocol bool 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); // } //}</click></click>
(注意:onTextFieldInsertText函数中是const char * text,使用的时候需要星号* text)
输入框,把锚点设置在(0.0,0.5),则会左对齐,此外如果这个修改了,也需要修改触摸的范围。
我习惯另外做一个显示的背景框,用作点击范围,这样用户使用比较方便。
CCTextFieldTTF相当灵活,方便我们自定义。很好!大赞!
参考资料:
http://blog.csdn.net/crayondeng/article/details/12175367 Cocos2d-x CCEditBox & CCTextFieldTTF

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











최근 많은 Win11 사용자가 입력 환경 대화 상자가 항상 깜박이고 끌 수 없는 문제에 직면했습니다. 이는 실제로 Win11의 기본 시스템 서비스 및 구성 요소로 인해 발생합니다. 먼저 관련 서비스를 비활성화한 다음 비활성화해야 합니다. 입력 경험 서비스, 해결해 볼까요? win11에서 입력 환경을 끄는 방법: 첫 번째 단계에서는 시작 메뉴를 마우스 오른쪽 버튼으로 클릭하고 "작업 관리자"를 엽니다. 두 번째 단계에서는 "CTF 로더", "MicrosoftIME" 및 "서비스 호스트: Textinput Management Service" 세 가지 프로세스를 찾습니다. 순서대로 "작업 끝내기"를 마우스 오른쪽 버튼으로 클릭합니다. "세 번째 단계는 시작 메뉴를 열고 상단의 "서비스"를 검색하여 엽니다. 네 번째 단계에서는 "Textinp"를 찾습니다.
![Windows 입력 시 중단 또는 높은 메모리 사용량이 발생함 [수정]](https://img.php.cn/upload/article/000/887/227/170835409686241.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
Windows 입력 환경은 다양한 휴먼 인터페이스 장치의 사용자 입력 처리를 담당하는 핵심 시스템 서비스입니다. 시스템이 시작되고 백그라운드에서 실행될 때 자동으로 시작됩니다. 그러나 때때로 이 서비스가 자동으로 중단되거나 너무 많은 메모리를 차지하여 시스템 성능이 저하될 수 있습니다. 따라서 시스템 효율성과 안정성을 보장하려면 이 프로세스를 적시에 모니터링하고 관리하는 것이 중요합니다. 이 문서에서는 Windows 입력 환경이 중단되거나 메모리 사용량이 높아지는 문제를 해결하는 방법을 공유합니다. Windows 입력 경험 서비스에는 사용자 인터페이스가 없지만 입력 장치와 관련된 기본적인 시스템 작업 및 기능을 처리하는 것과 밀접한 관련이 있습니다. 그 역할은 Windows 시스템이 사용자가 입력한 모든 입력을 이해하도록 돕는 것입니다.

검색 창은 win11 시스템에서 매우 유용한 기능으로, 원하는 설정, 기능 및 서비스를 찾는 데 도움이 됩니다. 그러나 일부 친구는 win11 검색창에 들어갈 수 없는 상황에 직면했습니다. 문제를 해결하기 위해 레지스트리에서 관련 데이터를 수정할 수 있습니다. win11 검색창을 입력할 수 없는 경우 해결 방법 1. 먼저 키보드에서 "win+r"을 눌러 실행을 불러옵니다. 2. 그런 다음 "regedit"를 입력하고 Enter를 눌러 레지스트리 편집기를 엽니다. 3. 그런 다음 위 경로에 "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Expl을 입력합니다.

행렬은 우리가 자주 사용하고 접하는 공식인데, 행렬을 단어로 입력하는 방법을 아시나요? 많은 분들이 한 번도 접해보지 않으셨을 수도 있고, 사용 시 헷갈리실 수도 있으니, 여기서는 단어 매트릭스를 입력하는 방법을 알려드리겠습니다. 이 기술을 공유하면 여러분에게 도움과 영감을 줄 수 있기를 바랍니다. 1. 먼저, 작업을 시연하기 위해 워드 문서를 만들고 엽니다. 아래 그림과 같이: 2. 행렬을 입력하려면 메뉴 표시줄에서 [삽입] 버튼을 찾아야 합니다. 이 버튼을 누르면 이 메뉴에서 사진 등 다양한 콘텐츠 옵션을 삽입할 수 있습니다. 술집. 3. [삽입]을 클릭한 후 도구 옵션 오른쪽에서 [수식]을 찾은 다음 [

문제 설명 공백으로 구분된 정수를 배열 입력으로 사용하는 C 프로그램을 작성하십시오. SampleExamples 입력 12345 출력 'Arrayelementsare-'1,2,3,4,5Explanation의 중국어 번역은 다음과 같습니다. 설명 입력에는 공백으로 구분된 5개의 정수가 포함되어 있습니다. 입력 997687542356878967343423 출력 'Arrayelementsare-'99,76,87,54,23,56,878,967,34,34,23 설명의 중국어 번역은 다음과 같습니다. 설명 입력에는 공백으로 구분된 11개의 정수가 포함되어 있습니다. 방법 1 이 방법에서는 입력을 빈 값으로 바꿉니다.

PHP 프로그래밍에서는 입력 내용에 숫자와 문자만 포함되어 있는지 확인하는 등 사용자가 입력하는 데이터를 제한해야 하는 경우가 있습니다. 실제 프로젝트 개발에서 자주 접하게 되는 문제이므로 이 기능을 어떻게 구현하는지 숙지하는 것이 매우 중요합니다. 이 기사에서는 PHP를 사용하여 입력에 숫자와 문자만 포함되어 있는지 확인하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. 입력에 숫자와 문자만 포함되어 있는지 확인해야 하는 이유는 무엇입니까? 웹사이트 개발 시, 사용자가 입력한 데이터는 데이터베이스 작업, 파일 작업 등 중요한 기능에 사용될 수 있습니다.

Python 부동 소수점 입력에 대한 참고 사항 및 예 Python에서 부동 소수점 숫자는 소수 부분으로 값을 나타내는 데 사용되는 일반적인 데이터 유형입니다. 부동 소수점 입력을 할 때 입력의 정확성과 정확성을 보장하기 위해 알아야 할 몇 가지 사항과 주의해야 할 사항이 있습니다. 이 문서에서는 몇 가지 일반적인 고려 사항을 소개하고 이해를 돕기 위해 샘플 코드를 제공합니다. 부동 소수점 입력 방법 Python에는 다음과 같은 다양한 부동 소수점 입력 방법이 있습니다. 입력에 부동 소수점 숫자를 직접 사용합니다. 예: x

1. PPT 소프트웨어를 열고 작동 인터페이스로 들어갑니다. 2. 이 인터페이스에서 삽입 옵션을 찾으세요. 3. 삽입 옵션을 클릭하고 하위 메뉴에서 특수 기호 옵션을 찾으세요. 4. 특수 기호 옵션을 클릭하면 특수 기호 삽입 대화 상자가 나타납니다. 5. 이 대화 상자에서 수학 기호 옵션을 찾으십시오. 6. 수학 기호 옵션을 클릭하고 그 안에서 기호와 같지 않음 옵션을 찾으세요. 7. 이 옵션을 클릭하면 부등식 기호가 입력 영역에 입력된 것을 볼 수 있습니다.
