首頁 資料庫 mysql教程 cocos2dx中的输入类CCTextFieldTTF的用法

cocos2dx中的输入类CCTextFieldTTF的用法

Jun 07, 2016 pm 03:09 PM
輸入

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


 

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

停用Win11輸入體驗指南 停用Win11輸入體驗指南 Dec 27, 2023 am 11:07 AM

最近有很多win11遇到了輸入體驗對話框總是閃爍,關也關不掉的問題,這其實是由於win11的默認系統服務和組件導致的,我們需要先禁用相關服務,再禁用輸入體驗服務就可以解決了,下面一起來試試看。 win11輸入體驗怎麼關閉:第一步,右鍵開始選單,開啟「任務管理器」第二步,依序找到「CTF載入程式」、「MicrosoftIME」和「服務主機:Textinputmanagementservice」三個進程,右鍵「結束任務」第三步,打開開始選單,在上方搜尋並打開「服務」第四步,在其中找到「Textinp

Windows輸入遇到掛起或記憶體使用率高的問題[修復] Windows輸入遇到掛起或記憶體使用率高的問題[修復] Feb 19, 2024 pm 10:48 PM

Windows的輸入體驗是關鍵的系統服務,負責處理來自各種人機介面設備的使用者輸入。它在系統啟動時自動啟動,在背景運行。然而,有時候這個服務可能會出現自動掛起或佔用過多記憶體的情況,導致系統效能下降。因此,及時監控和管理這個進程是至關重要的,以確保系統的效率和穩定性。在這篇文章中,我們將分享如何解決Windows輸入體驗被掛起或導致記憶體使用率高的問題。 Windows輸入體驗服務沒有使用者介面,但它與處理與輸入裝置相關的基本系統任務和功能有密切關聯。它的作用是幫助Windows系統理解使用者輸入的每一

解決win11搜尋欄輸入問題 解決win11搜尋欄輸入問題 Dec 26, 2023 pm 12:07 PM

搜尋列是win11系統中非常好用的功能,可以幫助我們找到想要的設定、功能和服務等。但是有的朋友遇到了win11搜尋欄無法輸入的情況,我們可以在註冊表中修改相關資料來解決,下面就跟著小編一起來解決一下吧。 win11搜尋列無法輸入怎麼辦1、首先我們可以按下鍵盤的「win+r」調出運行。 2、然後在其中輸入「regedit」回車確定開啟註冊表編輯器。 3、然後在上方路徑中輸入「HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Expl

word矩陣怎麼輸入 word矩陣怎麼輸入 Mar 19, 2024 pm 11:00 PM

矩陣是我們經常使用和遇到的公式,但是在word裡如何輸入矩陣你會操作嗎?很多人可能沒有接觸過,遇到使用的時候就會覺得困惑,那麼,這裡我們就跟大家分享一下word矩陣怎麼輸入。希望經過這個技巧的分享,能夠帶給你幫助和啟發。 1.首先,新建並開啟一個word文檔,為了示範操作,我們就使用空白文檔進行示範。如下圖所示:2.我們要輸入矩陣,需要在選單列找到【插入】按鈕,這個按鈕可以插入很多內容選項,例如圖片等都是從這個選單列完成。 3.點選【插入】之後,我們工具選項右邊看,可以找到【公式】,然後我們點選【

PHP實作指南:如何判斷輸入只包含數字和字母 PHP實作指南:如何判斷輸入只包含數字和字母 Mar 28, 2024 pm 03:06 PM

在PHP程式設計中,有時候我們需要對使用者輸入的資料進行限制,例如判斷輸入是否只包含數字和字母。這在實際專案開發中經常會遇到,因此掌握如何實現這項功能非常重要。本文將介紹如何使用PHP來判斷輸入只包含數字和字母,並給出具體的程式碼範例。為什麼需要判斷輸入只包含數字和字母?在網站開發中,使用者輸入的資料可能會被用於資料庫操作、文件操作等重要功能,如果使用者輸入的資料包含特

C程式輸入一個由空格分隔的整數序列的陣列 C程式輸入一個由空格分隔的整數序列的陣列 Aug 25, 2023 am 11:33 AM

問題陳述寫一個C程序,以空格分隔的整數作為數組輸入。 SampleExamples輸入12345輸出‘Arrayelementsare-’1,2,3,4,5Explanation的中文翻譯為:解釋輸入包含5個以空格分隔的整數。輸入997687542356878967343423輸出‘Arrayelementsare-’99,76,87,54,23,56,878,967,34,34,23Explanation的中文翻譯為:解釋輸入包含11個以空格分隔的整數。方法一在這種方法中,我們將把輸入中的以空

注意事項和範例:如何正確輸入Python中的浮點數 注意事項和範例:如何正確輸入Python中的浮點數 Feb 02, 2024 pm 06:34 PM

Python浮點型輸入的注意事項及範例在Python中,浮點數是一種常見的資料類型,用於表示帶有小數部分的數值。在進行浮點型輸入時,有一些注意事項需要我們了解並注意,以確保輸入的正確性和準確性。本文將介紹幾個常見的注意事項,並提供範例程式碼以加深理解。浮點型的輸入方式在Python中,浮點型的輸入方式有多種,常見的有以下幾種:直接使用浮點數進行輸入:例如:x

PPT輸入不等於符號的運算方法 PPT輸入不等於符號的運算方法 Mar 26, 2024 pm 03:21 PM

1.開啟PPT軟體,進入操作介面。 2、在這個介面內找到插入選項。 3.點選插入選項,在其子級選單中找到特殊符號選項。 4.點選特殊符號選項,彈出插入特殊符號對話框。 5.在該對話框內找到數學符號選項。 6.點選數學符號選項,在其內找到不等於符號選項。 7.點選該選項,可以看到再輸入區我們的不等於符號就輸入進來了。

See all articles