现在的位置: 首页 > 综合 > 正文

Cocos2d-x CCEditBox & CCTextFieldTTF

2018年04月20日 ⁄ 综合 ⁄ 共 39279字 ⁄ 字号 评论关闭

下面简单记录一下如何Cocos2d-x中创建输入编辑框。在引擎中为我们提供了这样两个类:CCEditBox  和  CCTextFieldTTF。

一、CCEditBox

①这个类文件的位置


②这个类是继承自 CCControlButton 和 CCIMEDelegate。其中的CCIMEDelegate代理类中定义了四个代理方法,在使用的时候根据需要选择实现相应的委托方法,从方法名就可以大致知道是什么意思了。

  1. class CCEditBoxDelegate    
  2. {   
  3. public:   
  4.     virtual ~CCEditBoxDelegate() {};   
  5.        
  6.     /**  
  7.      * This method is called when an edit box gains focus after keyboard is shown.
     
  8.      * @param editBox The edit box object that generated the event.
     
  9.      */  
  10.     virtual void editBoxEditingDidBegin(CCEditBox* editBox) {};   
  11.        
  12.        
  13.     /**  
  14.      * This method is called when an edit box loses focus after keyboard is hidden.
     
  15.      * @param editBox The edit box object that generated the event.
     
  16.      */  
  17.     virtual void editBoxEditingDidEnd(CCEditBox* editBox) {};   
  18.        
  19.     /**  
  20.      * This method is called when the edit box text was changed.
     
  21.      * @param editBox The edit box object that generated the event.
     
  22.      * @param text The new text.  
  23.      */  
  24.     virtual void editBoxTextChanged(CCEditBox* editBox, const std::string& text) {};   
  25.        
  26.     /**  
  27.      * This method is called when the return button was pressed or the outside area of keyboard was touched.
     
  28.      * @param editBox The edit box object that generated the event.
     
  29.      */  
  30.     virtual void editBoxReturn(CCEditBox* editBox) = 0;   
  31.        
  32. };  


下面通过一个demo来使用一下 CCEditBox 这个类中的相关方法(通过查看该类的头文件可知道更加详细的方法介绍)。

注意:使用的时候需要:

#include "cocos-ext.h"

USING_NS_CC_EXT;


 头文件:

  1. class HelloWorld : public cocos2d::CCLayer,public CCEditBoxDelegate   
  2. {   
  3. public:   
  4.     // Method 'init' in cocos2d-x returns bool, instead of 'id' in cocos2d-iphone (an object pointer)
      
  5.     virtual bool init();   
  6.   
  7.     // there's no 'id' in cpp, so we recommend to return the class instance pointer
      
  8.     static cocos2d::CCScene* scene();   
  9.        
  10.     // a selector callback   
  11.     void menuCloseCallback(CCObject* pSender);   
  12.   
  13.     // preprocessor macro for "static create()" constructor ( node() deprecated )
      
  14.     CREATE_FUNC(HelloWorld);   
  15.        
  16.     virtual void editBoxEditingDidBegin(cocos2d::extension::CCEditBox* editBox);   
  17.     virtual void editBoxEditingDidEnd(cocos2d::extension::CCEditBox* editBox);   
  18.     virtual void editBoxTextChanged(cocos2d::extension::CCEditBox* editBox, const std::string& text);   
  19.     virtual void editBoxReturn(cocos2d::extension::CCEditBox* editBox);   
  20.        
  21. private:   
  22.     CCEditBox* editBox;   
  23.        
  24. };  

实现文件:

  1. <PRE class=cpp name="code">bool HelloWorld::init()
      
  2. {   
  3.     //////////////////////////////
      
  4.     // 1. super init first   
  5.     if ( !CCLayer::init() )   
  6.     {   
  7.         return false;   
  8.     }   
  9.        
  10.     CCSize winSize = CCDirector::sharedDirector()->getWinSize();   
  11.     CCSize editSize = CCSizeMake(300, 50);   
  12.     //第一个size参数表示输入编辑框的大小,第二个参数九宫格是用于输入编辑框的背景
      
  13.     editBox = CCEditBox::create(editSize, CCScale9Sprite::create("12.png"));   
  14.        
  15.     editBox->cocos2d::CCNode::setPosition(winSize.width/2, winSize.height-80);   
  16.        
  17.     //以setFont开头的有几个方法是 用于设置输入文字的字体,大小,颜色
      
  18.     editBox->setFontSize(25);   
  19.     editBox->setFontColor(ccRED);   
  20.        
  21.     //设置输入编辑框在还没有输入的时候默认的提示文字
      
  22.     editBox->setPlaceHolder("Name: ");   
  23.        
  24.     //同样的,也有几个对应的方法的是用于设置这些提示文字的,都是以setPlaceHolder开头的
      
  25.     editBox->setPlaceholderFontColor(ccWHITE);   
  26.        
  27.     //设置输入编辑文字的长度,一个字符为一个长度
      
  28.     editBox->setMaxLength(20);   
  29.        
  30.     //设置键盘中return键显示的字符   
  31.     editBox->setReturnType(kKeyboardReturnTypeGo);   
  32.     //包括这些选项   
  33.     //      kKeyboardReturnTypeDefault:  默认使用键盘return 类型
      
  34.     //      kKeyboardReturnTypeDone:     默认使用键盘return类型为“Done”字样
      
  35.     //      kKeyboardReturnTypeSend:     默认使用键盘return类型为“Send”字样
      
  36.     //      kKeyboardReturnTypeSearch:   默认使用键盘return类型为“Search”字样
      
  37.     //      kKeyboardReturnTypeGo:       默认使用键盘return类型为“Go”字样
      
  38.        
  39.     //设置输入编辑框的编辑类型   
  40.     editBox->setInputMode(kEditBoxInputModeAny);   
  41.     //包括这些选项   
  42.     //      kEditBoxInputModeAny:         开启任何文本的输入键盘,包括换行
      
  43.     //      kEditBoxInputModeEmailAddr:   开启 邮件地址 输入类型键盘
      
  44.     //      kEditBoxInputModeNumeric:     开启 数字符号 输入类型键盘
      
  45.     //      kEditBoxInputModePhoneNumber: 开启 电话号码 输入类型键盘
      
  46.     //      kEditBoxInputModeUrl:         开启 URL 输入类型键盘
      
  47.     //      kEditBoxInputModeDecimal:     开启 数字 输入类型键盘,允许小数点
      
  48.     //      kEditBoxInputModeSingleLine:  开启任何文本的输入键盘,不包括换行
      
  49.        
  50.     //设置该属性输入密码时为替代符   
  51. //    editBox->setInputFlag(kEditBoxInputFlagPassword);  //如果只是简单输入字符,则不用这个设置
      
  52.     //包括这些选项   
  53.     //    kEditBoxInputFlagPassword,
      
  54.     //    kEditBoxInputFlagSensitive,
      
  55.     //    kEditBoxInputFlagInitialCapsWord,
      
  56.     //    kEditBoxInputFlagInitialCapsSentence,
      
  57.     //    kEditBoxInputFlagInitialCapsAllCharacters
      
  58.        
  59.     //设置委托代理对象为当前类   
  60.     editBox->setDelegate(this);   
  61.        
  62.        
  63.     this->addChild(editBox);   
  64.        
  65.     return true;   
  66. }</PRE><BR><BR>  


委托方法可以根据需要自定义实现相关的内容。

  1. void HelloWorld::editBoxEditingDidBegin(cocos2d::extension::CCEditBox *editBox)   
  2. {   
  3.        
  4. }   
  5.   
  6. void HelloWorld::editBoxEditingDidEnd(cocos2d::extension::CCEditBox *editBox)   
  7. {   
  8.        
  9. }   
  10.   
  11. void HelloWorld::editBoxTextChanged(cocos2d::extension::CCEditBox *editBox, const std::string &text)   
  12. {   
  13.        
  14. }   
  15.   
  16. void HelloWorld::editBoxReturn(cocos2d::extension::CCEditBox *editBox)   
  17. {   
  18.     CCLOG("the text = %s",editBox->getText());   
  19. }  


下面有一点要提示:本人在使用过程中遇到过这样一个问题,创建好对象添加到layer中的时候,点击编辑框,没有响应(没有调出键盘),debug了好一会才发现,是触摸层级的问题,后来修改了layer的触摸等级(降低了layer的优先级),就可以了。

二、CCTextFieldTTF

①这个类文件的位置

libs/cocos2dx/text_input_node/

②这个类是继承了 CCLabelTTF 和  CCIMEDelegate

通过其继承了CCLabelTTF这个类和 CCIMEDelegate 键盘代理类。

根据其继承自CCLabelTTF,我们就可以大致猜测到其实现了,估计就是一个动态的 CCLabelTTF ,通过不断监听输入的字符,动态设置 label 的字符,进行显示而已吧!

而其继承 CCIMEDelegate 这个键盘代理类,其中的代理方法主要是处理键盘的出现和隐藏过程中的一些自定义过程实现,如果需要,可以继承这个类,并重写其中的相关方法。


另外,在layer中使用CCTextFieldTTF创建输入编辑框对象的时候,需要继承 CCTextFieldDelegate 这个代理类,其中也定义了相关的委托方法,使用的时候根据需要选择实现即可。

而这个 CCTextFieldDelegate 委托方法主要是处理在编辑输入框键入字符过程中的一些自定义实现。下面就是这个代理类中的相关方法,看方法名就知道键入字符分成四个过程了。

  1. class CC_DLL CCTextFieldDelegate   
  2. {   
  3. public:   
  4.     /**  
  5.     @brief    If the sender doesn't want to attach to the IME, return true;
     
  6.     */  
  7.     virtual bool onTextFieldAttachWithIME(CCTextFieldTTF * sender)   
  8.     {   
  9.         CC_UNUSED_PARAM(sender);   
  10.         return false;   
  11.     }   
  12.   
  13.     /**  
  14.     @brief    If the sender doesn't want to detach from the IME, return true;
     
  15.     */  
  16.     virtual bool onTextFieldDetachWithIME(CCTextFieldTTF * sender)   
  17.     {   
  18.         CC_UNUSED_PARAM(sender);   
  19.         return false;   
  20.     }   
  21.   
  22.     /**  
  23.     @brief    If the sender doesn't want to insert the text, return true;
     
  24.     */  
  25.     virtual bool onTextFieldInsertText(CCTextFieldTTF * sender, const char * text, int nLen)
      
  26.     {   
  27.         CC_UNUSED_PARAM(sender);   
  28.         CC_UNUSED_PARAM(text);   
  29.         CC_UNUSED_PARAM(nLen);   
  30.         return false;   
  31.     }   
  32.   
  33.     /**  
  34.     @brief    If the sender doesn't want to delete the delText, return true;
     
  35.     */  
  36.     virtual bool onTextFieldDeleteBackward(CCTextFieldTTF * sender, const char * delText, int nLen)
      
  37.     {   
  38.         CC_UNUSED_PARAM(sender);   
  39.         CC_UNUSED_PARAM(delText);   
  40.         CC_UNUSED_PARAM(nLen);   
  41.         return false;   
  42.     }   
  43.   
  44.     /**  
  45.     @brief    If the sender doesn't want to draw, return true.
     
  46.     */  
  47.     virtual bool onDraw(CCTextFieldTTF * sender)   
  48.     {   
  49.         CC_UNUSED_PARAM(sender);   
  50.         return false;   
  51.     }   
  52. };  

其中的方法 return true或者false要注意!(看方法前面的注释)


下面通过testcpp中的一个 TextFieldTTFActionTest 来具体实践一下(本人抽离出相关的代码并做了相应的补充修改)

简单对程序说明一下:实现了键盘出现和隐藏时候的视图内容的自动调整,同时在输入字符和删除字符的时候有动作特效。

还有就是键盘的锚地位置是在其左下角,在键盘出现和隐藏方法中输出的数值中就可以发现。


我的测试的过程中有一个特别坑的bug,就是在onEnter这个方法中,忘了 CCLayer::onEnter(); 对父类的调用,所以导致程序莫名其妙的问题(无法执行动作),找了好久,看到http://blog.csdn.net/somestill/article/details/9875743这篇文章后,才找出这个bug。


下面直接贴出代码,看懂应该没有什么问题。


头文件:

  1. #ifndef __HELLOWORLD_SCENE_H__
      
  2. #define __HELLOWORLD_SCENE_H__
      
  3.   
  4. #include "cocos2d.h"   
  5. USING_NS_CC;   
  6.   
  7. class HelloWorld : public cocos2d::CCLayer,public CCTextFieldDelegate,public CCIMEDelegate
      
  8. {   
  9. public:   
  10.     // Method 'init' in cocos2d-x returns bool, instead of 'id' in cocos2d-iphone (an object pointer)
      
  11.     virtual bool init();   
  12.   
  13.     // there's no 'id' in cpp, so we recommend to return the class instance pointer
      
  14.     static cocos2d::CCScene* scene();   
  15.        
  16.     // preprocessor macro for "static create()" constructor ( node() deprecated )
      
  17.     CREATE_FUNC(HelloWorld);   
  18.        
  19.     void callbackRemoveNodeWhenDidAction(CCNode * pNode);   
  20.     virtual void onClickTrackNode(bool bClicked);   
  21.        
  22.     // CCLayer   
  23.     virtual void onEnter();   
  24.     virtual void onExit();   
  25.     virtual void registerWithTouchDispatcher();   
  26.     virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);   
  27.     virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);   
  28.        
  29.     // CCTextFieldDelegate
      
  30.     virtual bool onTextFieldAttachWithIME(CCTextFieldTTF * pSender);   
  31.     virtual bool onTextFieldDetachWithIME(CCTextFieldTTF * pSender);   
  32.     virtual bool onTextFieldInsertText(CCTextFieldTTF * pSender, const char * text, int nLen);
      
  33.     virtual bool onTextFieldDeleteBackward(CCTextFieldTTF * pSender, const char * delText, int nLen);
      
  34.     virtual bool onDraw(CCTextFieldTTF * pSender);   
  35.   
  36.     //CCIMEDelegate   
  37.     //keyboard show/hide notification
      
  38.     virtual void keyboardWillShow(CCIMEKeyboardNotificationInfo& info);   
  39.     virtual void keyboardWillHide(CCIMEKeyboardNotificationInfo& info);   
  40.        
  41. private:   
  42.     CCTextFieldTTF*     m_pTextField;   
  43.     CCAction*           m_pTextFieldAction;   
  44.     bool                m_bAction;   
  45.     int                 m_nCharLimit;       // the textfield max char limit
      
  46.     CCPoint  m_beginPos;   
  47.     float adjustVert;   
  48. };   
  49.   
  50. #endif // __HELLOWORLD_SCENE_H__  


实现文件:

  1. #include "HelloWorldScene.h"
      
  2. #include "SimpleAudioEngine.h"
      
  3.   
  4. using namespace cocos2d;   
  5. using namespace CocosDenshion;   
  6.   
  7. #define FONT_NAME                       "Thonburi"
      
  8. #define FONT_SIZE                       36
      
  9.   
  10. CCScene* HelloWorld::scene()   
  11. {   
  12.     // 'scene' is an autorelease object
      
  13.     CCScene *scene = CCScene::create();   
  14.        
  15.     // 'layer' is an autorelease object
      
  16.     HelloWorld *layer = HelloWorld::create();   
  17.   
  18.     // add layer as a child to scene
      
  19.     scene->addChild(layer);   
  20.   
  21.     // return the scene
      
  22.     return scene;   
  23. }   
  24.   
  25. // on "init" you need to initialize your instance
      
  26. bool HelloWorld::init()   
  27. {   
  28.     //////////////////////////////
      
  29.     // 1. super init first
      
  30.     if ( !CCLayer::init() )   
  31.     {   
  32.         return false;   
  33.     }   
  34.        
  35.     setTouchEnabled(true);  //注意要设置当前layer为可触摸
      
  36.        
  37.     CCSize size = CCDirector::sharedDirector()->getWinSize();   
  38.     CCSprite* pSprite = CCSprite::create("HelloWorld.png");   
  39.     pSprite->setPosition( ccp(size.width/2, size.height/2) );   
  40.     this->addChild(pSprite, 0);   
  41.        
  42.        
  43.     return true;   
  44. }   
  45.   
  46. void HelloWorld::registerWithTouchDispatcher()   
  47. {   
  48.     CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);   
  49. }   
  50.   
  51. void HelloWorld::onEnter()   
  52. {   
  53.     CCLayer::onEnter(); //这个父类的调用很重要!
      
  54.        
  55.     m_nCharLimit = 12;   
  56.     m_pTextFieldAction = CCRepeatForever::create(   
  57.                                                  CCSequence::create(   
  58.                                                                     CCFadeOut::create(0.25),   
  59.                                                                     CCFadeIn::create(0.25),   
  60.                                                                     NULL   
  61.                                                                     ));   
  62.     m_pTextFieldAction->retain();  //这里一定要retain一次,否则会出现内存问题。
      
  63.        
  64.     m_bAction = false;   
  65.        
  66.     // add CCTextFieldTTF   
  67.     CCSize s = CCDirector::sharedDirector()->getWinSize();   
  68.     m_pTextField = CCTextFieldTTF::textFieldWithPlaceHolder("<click here for input>",   
  69.                                                             FONT_NAME,   
  70.                                                             FONT_SIZE);   
  71.     m_pTextField->setColor(ccWHITE);  //设置输入编辑框中字符的颜色
      
  72. //    m_pTextField->setSecureTextEntry(true); //输入密码时,用点字符替代
      
  73.     m_pTextField->setDelegate(this);    
  74.     m_pTextField->setPosition(ccp(s.width / 2, s.height / 2-30)); //将输入编辑框的y轴位置设低是为了测试,当出现键盘的时候,输入编辑框的自动向上调整。
      
  75.     addChild(m_pTextField);   
  76. }   
  77.   
  78. //返回节点的rect   
  79. static CCRect getRect(CCNode * pNode)   
  80. {   
  81.     CCRect rc;   
  82.     rc.origin = pNode->getPosition();   
  83.     rc.size = pNode->getContentSize();   
  84.     rc.origin.x -= rc.size.width / 2;   
  85.     rc.origin.y -= rc.size.height / 2;   
  86.     return rc;   
  87. }   
  88.   
  89. bool HelloWorld::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)   
  90. {   
  91.     CCLOG("++++++++++++++++++++++++++++++++++++++++++++");   
  92.     m_beginPos = pTouch->getLocation();   
  93.     return true;   
  94. }   
  95.   
  96. void HelloWorld::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)   
  97. {   
  98.     if (! m_pTextField)   
  99.     {   
  100.         return;   
  101.     }   
  102.        
  103.     CCPoint endPos = pTouch->getLocation();   
  104.        
  105.     // 以下这部分代码是用于检测 begin touch 到 end touch之间的距离是否超过5.0,如果是,则返回;否则,继续执行下面的判断是否点击到编辑框的代码。
      
  106.     float delta = 5.0f;   
  107.     if (::abs(endPos.x - m_beginPos.x) > delta   
  108.         || ::abs(endPos.y - m_beginPos.y) > delta)   
  109.     {   
  110.         // not click   
  111.         m_beginPos.x = m_beginPos.y = -1;   
  112.         return;   
  113.     }   
  114.        
  115.     // decide the trackNode is clicked.
      
  116.     CCRect rect;   
  117.     rect = getRect(m_pTextField);   
  118.     this->onClickTrackNode(rect.containsPoint(endPos));   
  119.     CCLOG("----------------------------------");   
  120. }   
  121.   
  122. void HelloWorld::onClickTrackNode(bool bClicked)   
  123. {   
  124.     if (bClicked)   
  125.     {   
  126.         // TextFieldTTFTest be clicked
      
  127.         CCLOG("attachWithIME");   
  128.         m_pTextField->attachWithIME(); //调用键盘
      
  129.     }   
  130.     else  
  131.     {   
  132.         // TextFieldTTFTest not be clicked
      
  133.         CCLOG("detachWithIME");   
  134.         m_pTextField->detachWithIME(); //隐藏键盘
      
  135.     }   
  136. }   
  137.   
  138.   
  139. void HelloWorld::onExit()   
  140. {   
  141.     m_pTextFieldAction->release();   
  142.     CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);   
  143. }   
  144.   
  145.   
  146.   
  147. // CCTextFieldDelegate protocol
      
  148. bool HelloWorld::onTextFieldAttachWithIME(CCTextFieldTTF * pSender)   
  149. {   
  150.     if (! m_bAction)   
  151.     {   
  152.         m_pTextField->runAction(m_pTextFieldAction);   
  153.         m_bAction = true;   
  154.     }   
  155.     return false;   
  156. }   
  157.   
  158. bool HelloWorld::onTextFieldDetachWithIME(CCTextFieldTTF * pSender)   
  159. {   
  160.     if (m_bAction)   
  161.     {   
  162.         m_pTextField->stopAction(m_pTextFieldAction);   
  163.         m_pTextField->setOpacity(255);   
  164.         m_bAction = false;   
  165.     }   
  166.     return false;   
  167. }   
  168.   
  169. bool HelloWorld::onTextFieldInsertText(CCTextFieldTTF * pSender, const char * text, int nLen)
      
  170. {   
  171.     // if insert enter, treat as default to detach with ime
      
  172.     if ('\n' == *text)   
  173.     {   
  174.         return false;   
  175.     }   
  176.        
  177.     // if the textfield's char count more than m_nCharLimit, doesn't insert text anymore.
      
  178.     if (pSender->getCharCount() >= m_nCharLimit)   
  179.     {   
  180.         return true;   
  181.     }   
  182.        
  183.     // create a insert text sprite and do some action
      
  184.     CCLabelTTF * label = CCLabelTTF::create(text, FONT_NAME, FONT_SIZE);   
  185.     this->addChild(label);   
  186.     ccColor3B color = { 226, 121, 7};   
  187.     label->setColor(color);   
  188.        
  189.     // move the sprite from top to position
      
  190.     CCPoint endPos = pSender->getPosition();   
  191.     if (pSender->getCharCount())   
  192.     {   
  193.         endPos.x += pSender->getContentSize().width / 2;   
  194.     }   
  195.     CCSize  inputTextSize = label->getContentSize();   
  196.     CCPoint beginPos(endPos.x, CCDirector::sharedDirector()->getWinSize().height - inputTextSize.height * 2);   
  197.        
  198.     float duration = 0.5;   
  199.     label->setPosition(beginPos);   
  200.     label->setScale(8);   
  201.        
  202.     CCAction * seq = CCSequence::create(   
  203.                                         CCSpawn::create(   
  204.                                                         CCMoveTo::create(duration, endPos),   
  205.                                                         CCScaleTo::create(duration, 1),   
  206.                                                         CCFadeOut::create(duration),   
  207.                                                         0),   
  208.                                         CCCallFuncN::create(this, callfuncN_selector(HelloWorld::callbackRemoveNodeWhenDidAction)),   
  209.                                         0);   
  210.     label->runAction(seq);   
  211.     return false;   
  212. }   
  213.   
  214. bool HelloWorld::onTextFieldDeleteBackward(CCTextFieldTTF * pSender, const char * delText, int nLen)
      
  215. {   
  216.     // create a delete text sprite and do some action
      
  217.     CCLabelTTF * label = CCLabelTTF::create(delText, FONT_NAME, FONT_SIZE);   
  218.     this->addChild(label);   
  219.        
  220.     // move the sprite to fly out   
  221.     CCPoint beginPos = pSender->getPosition();   
  222.     CCSize textfieldSize = pSender->getContentSize();   
  223.     CCSize labelSize = label->getContentSize();   
  224.     beginPos.x += (textfieldSize.width - labelSize.width) / 2.0f;   
  225.        
  226.     CCSize winSize = CCDirector::sharedDirector()->getWinSize();   
  227.     CCPoint endPos(- winSize.width / 4.0f, winSize.height * (0.5 + (float)rand() / (2.0f * RAND_MAX)));   
  228.        
  229.     float duration = 1;   
  230.     float rotateDuration = 0.2f;   
  231.     int repeatTime = 5;   
  232.     label->setPosition(beginPos);   
  233.        
  234.     CCAction * seq = CCSequence::create(   
  235.                                         CCSpawn::create(   
  236.                                                         CCMoveTo::create(duration, endPos),   
  237.                                                         CCRepeat::create(   
  238.                                                                          CCRotateBy::create(rotateDuration, (rand()%2) ? 360 : -360),   
  239.                                                                          repeatTime),   
  240.                                                         CCFadeOut::create(duration),   
  241.                                                         0),   
  242.                                         CCCallFuncN::create(this, callfuncN_selector(HelloWorld::callbackRemoveNodeWhenDidAction)),   
  243.                                         0);   
  244.     label->runAction(seq);   
  245.     return false;   
  246. }   
  247.   
  248. bool HelloWorld::onDraw(CCTextFieldTTF * pSender)   
  249. {   
  250.     return false;   
  251. }   
  252.   
  253. void HelloWorld::callbackRemoveNodeWhenDidAction(CCNode * pNode)   
  254. {   
  255.     this->removeChild(pNode, true);   
  256. }   
  257.   
  258. void HelloWorld::keyboardWillShow(CCIMEKeyboardNotificationInfo& info)   
  259. {   
  260.     CCLOG("TextInputTest:keyboardWillShowAt(origin:%f,%f, size:%f,%f)",   
  261.           info.end.origin.x, info.end.origin.y, info.end.size.width, info.end.size.height);   
  262.        
  263.     if (! m_pTextField)   
  264.     {   
  265.         return;   
  266.     }   
  267.        
  268.     CCRect rectTracked = getRect(m_pTextField);   
  269.        
  270.     CCLOG("TextInputTest:trackingNodeAt(origin:%f,%f, size:%f,%f)",   
  271.           rectTracked.origin.x, rectTracked.origin.y, rectTracked.size.width, rectTracked.size.height);   
  272.        
  273.     // if the keyboard area doesn't intersect with the tracking node area, nothing need to do.
      
  274.     if (! rectTracked.intersectsRect(info.end))   
  275.     {   
  276.         return;   
  277.     }   
  278.        
  279.     // assume keyboard at the bottom of screen, calculate the vertical adjustment.
      
  280.        
  281.     //计算出需要y轴需要调整的距离   
  282.     adjustVert = info.end.getMaxY() - rectTracked.getMinY();   
  283.     CCLOG("TextInputTest:needAdjustVerticalPosition(%f)", adjustVert);   
  284.        
  285.     // move all the children node of KeyboardNotificationLayer
      
  286.     CCArray * children = getChildren();   
  287.     CCNode * node = 0;   
  288.     int count = children->count();   
  289.     CCPoint pos;   
  290.     for (int i = 0; i < count; ++i)   
  291.     {   
  292.         node = (CCNode*)children->objectAtIndex(i);   
  293.         pos = node->getPosition();   
  294.         pos.y += adjustVert;  //所有的节点都向上移动
      
  295.         node->setPosition(pos);   
  296.     }   
  297. }   
  298.   
  299.   
  300. void HelloWorld::keyboardWillHide(CCIMEKeyboardNotificationInfo &info)   
  301. {   
  302.     CCLOG("TextInputTest:keyboardWillShowAt(origin:%f,%f, size:%f,%f)",   
  303.           info.end.origin.x, info.end.origin.y, info.end.size.width, info.end.size.height);   
  304.        
  305.     CCArray * children = getChildren();   
  306.     CCNode * node = 0;   
  307.     int count = children->count();   
  308.     CCPoint pos;   
  309.     for (int i = 0; i < count; ++i)   
  310.     {   
  311.         node = (CCNode*)children->objectAtIndex(i);   
  312.         pos = node->getPosition();   
  313.         pos.y -= adjustVert;  //所有的节点都向下移动,恢复原来的位置
      
  314.         node->setPosition(pos);   
  315.     }   
  316. }  

大概就是这么多内容了吧!了解了一下CCEditBox  &  CCTextFieldTTF,感觉前者使用过程比较简单,后者比较复杂一些,但是可以增加一些特殊效果。


还有一点就是:使用 CCEditBox 创建的编辑框,不用额外的代码处理,点击编辑框区域就可以跳出键盘,点击非编辑框区域就可以隐藏键盘;


但是使用CCTextFieldTTF创建编辑框的时候,点击编辑框的时候,需要添加检测判断的代码,判断点击位置是否在编辑框中(在touch触摸事件中处理),如果是,才手动调用方法,弹出键盘;这个弹出键盘的处理在上面的代码中已经有涉及。同理,如果想要实现点击非编辑框区域,隐藏键盘,同样需要添加代码检测判断点击位置是否落在非编辑框区域。所以说后者的使用比较麻烦!


抱歉!评论已关闭.