찾다
데이터 베이스MySQL 튜토리얼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


 

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
MySQL : 초보자가 마스터하는 필수 기술MySQL : 초보자가 마스터하는 필수 기술Apr 18, 2025 am 12:24 AM

MySQL은 초보자가 데이터베이스 기술을 배우는 데 적합합니다. 1. MySQL 서버 및 클라이언트 도구를 설치하십시오. 2. SELECT와 같은 기본 SQL 쿼리를 이해하십시오. 3. 마스터 데이터 작업 : 데이터를 만들고, 삽입, 업데이트 및 삭제합니다. 4. 고급 기술 배우기 : 하위 쿼리 및 창 함수. 5. 디버깅 및 최적화 : 구문 확인, 인덱스 사용, 선택*을 피하고 제한을 사용하십시오.

MySQL : 구조화 된 데이터 및 관계형 데이터베이스MySQL : 구조화 된 데이터 및 관계형 데이터베이스Apr 18, 2025 am 12:22 AM

MySQL은 테이블 구조 및 SQL 쿼리를 통해 구조화 된 데이터를 효율적으로 관리하고 외래 키를 통해 테이블 ​​간 관계를 구현합니다. 1. 테이블을 만들 때 데이터 형식을 정의하고 입력하십시오. 2. 외래 키를 사용하여 테이블 간의 관계를 설정하십시오. 3. 인덱싱 및 쿼리 최적화를 통해 성능을 향상시킵니다. 4. 데이터 보안 및 성능 최적화를 보장하기 위해 데이터베이스를 정기적으로 백업 및 모니터링합니다.

MySQL : 주요 기능 및 기능이 설명되었습니다MySQL : 주요 기능 및 기능이 설명되었습니다Apr 18, 2025 am 12:17 AM

MySQL은 웹 개발에 널리 사용되는 오픈 소스 관계형 데이터베이스 관리 시스템입니다. 주요 기능에는 다음이 포함됩니다. 1. 다른 시나리오에 적합한 InnoDB 및 MyISAM과 같은 여러 스토리지 엔진을 지원합니다. 2.로드 밸런싱 및 데이터 백업을 용이하게하기 위해 마스터 슬레이브 복제 기능을 제공합니다. 3. 쿼리 최적화 및 색인 사용을 통해 쿼리 효율성을 향상시킵니다.

SQL의 목적 : MySQL 데이터베이스와 상호 작용합니다SQL의 목적 : MySQL 데이터베이스와 상호 작용합니다Apr 18, 2025 am 12:12 AM

SQL은 MySQL 데이터베이스와 상호 작용하여 데이터 첨가, 삭제, 수정, 검사 및 데이터베이스 설계를 실현하는 데 사용됩니다. 1) SQL은 Select, Insert, Update, Delete 문을 통해 데이터 작업을 수행합니다. 2) 데이터베이스 설계 및 관리에 대한 생성, 변경, 삭제 문을 사용하십시오. 3) 복잡한 쿼리 및 데이터 분석은 SQL을 통해 구현되어 비즈니스 의사 결정 효율성을 향상시킵니다.

초보자를위한 MySQL : 데이터베이스 관리를 시작합니다초보자를위한 MySQL : 데이터베이스 관리를 시작합니다Apr 18, 2025 am 12:10 AM

MySQL의 기본 작업에는 데이터베이스, 테이블 작성 및 SQL을 사용하여 데이터에서 CRUD 작업을 수행하는 것이 포함됩니다. 1. 데이터베이스 생성 : createAbasemy_first_db; 2. 테이블 만들기 : CreateTableBooks (idintauto_incrementprimarykey, titlevarchar (100) notnull, authorvarchar (100) notnull, published_yearint); 3. 데이터 삽입 : InsertIntobooks (Title, Author, Published_year) VA

MySQL의 역할 : 웹 응용 프로그램의 데이터베이스MySQL의 역할 : 웹 응용 프로그램의 데이터베이스Apr 17, 2025 am 12:23 AM

웹 응용 프로그램에서 MySQL의 주요 역할은 데이터를 저장하고 관리하는 것입니다. 1. MySQL은 사용자 정보, 제품 카탈로그, 트랜잭션 레코드 및 기타 데이터를 효율적으로 처리합니다. 2. SQL 쿼리를 통해 개발자는 데이터베이스에서 정보를 추출하여 동적 컨텐츠를 생성 할 수 있습니다. 3.mysql은 클라이언트-서버 모델을 기반으로 작동하여 허용 가능한 쿼리 속도를 보장합니다.

MySQL : 첫 번째 데이터베이스 구축MySQL : 첫 번째 데이터베이스 구축Apr 17, 2025 am 12:22 AM

MySQL 데이터베이스를 구축하는 단계에는 다음이 포함됩니다. 1. 데이터베이스 및 테이블 작성, 2. 데이터 삽입 및 3. 쿼리를 수행하십시오. 먼저 CreateAbase 및 CreateTable 문을 사용하여 데이터베이스 및 테이블을 작성한 다음 InsertInto 문을 사용하여 데이터를 삽입 한 다음 최종적으로 SELECT 문을 사용하여 데이터를 쿼리하십시오.

MySQL : 데이터 저장에 대한 초보자 친화적 인 접근 방식MySQL : 데이터 저장에 대한 초보자 친화적 인 접근 방식Apr 17, 2025 am 12:21 AM

MySQL은 사용하기 쉽고 강력하기 때문에 초보자에게 적합합니다. 1.MySQL은 관계형 데이터베이스이며 CRUD 작업에 SQL을 사용합니다. 2. 설치가 간단하고 루트 사용자 비밀번호를 구성해야합니다. 3. 삽입, 업데이트, 삭제 및 선택하여 데이터 작업을 수행하십시오. 4. Orderby, Where and Join은 복잡한 쿼리에 사용될 수 있습니다. 5. 디버깅은 구문을 확인하고 쿼리를 분석하기 위해 설명을 사용해야합니다. 6. 최적화 제안에는 인덱스 사용, 올바른 데이터 유형 선택 및 우수한 프로그래밍 습관이 포함됩니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전