Home Database Mysql Tutorial cocos2dx中的输入类CCTextFieldTTF的用法

cocos2dx中的输入类CCTextFieldTTF的用法

Jun 07, 2016 pm 03:09 PM
enter

cocos2dx中的输入类CCTextFieldTTF。还是相当好用的, 其中,很多人都会关注怎么判断用户输入的数字,字母,汉字? 通过重载onTextFieldInsertText函数,我们可以自定义自己想要的效果。 以下代码,是参考官方的示例,添加了是否数字、字母、汉字的判断,还

cocos2dx中的输入类CCTextFieldTTF。还是相当好用的,

其中,很多人都会关注怎么判断用户输入的数字,字母,汉字?

通过重载onTextFieldInsertText函数,我们可以自定义自己想要的效果。

以下代码,是参考官方的示例,添加了是否数字、字母、汉字的判断,还增加了以空格和回车作为输入结束符。

以下代码,拷到新建项目的HelloWorld中可以直接用(本文版本cocos2dx 2.2.2)。

 

上代码: .h文件

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

#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__

Copy after login


 

 

.cpp文件

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

#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>

Copy after login


 

 

 

 

(注意:onTextFieldInsertText函数中是const char * text,使用的时候需要星号* text)

 

输入框,把锚点设置在(0.0,0.5),则会左对齐,此外如果这个修改了,也需要修改触摸的范围。

我习惯另外做一个显示的背景框,用作点击范围,这样用户使用比较方便。

CCTextFieldTTF相当灵活,方便我们自定义。很好!大赞!

 

参考资料:

http://blog.csdn.net/crayondeng/article/details/12175367 Cocos2d-x CCEditBox & CCTextFieldTTF


 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Disabling Win11 Input Experience Guide Disabling Win11 Input Experience Guide Dec 27, 2023 am 11:07 AM

Recently, many Win11 users have encountered the problem that the input experience dialog box always flickers and cannot be turned off. This is actually caused by the default system services and components of Win11. We need to disable the relevant services first, and then disable the input experience service. Solved, let’s try it out together. How to turn off the input experience in win11: First step, right-click the start menu and open "Task Manager". Second step, find the three processes "CTF Loader", "MicrosoftIME" and "Service Host: Textinput Management Service" in order, right-click "End Task" "The third step, open the start menu, search and open "Services" at the top. The fourth step, find "Textinp" in it

Windows input encounters hang or high memory usage [Fix] Windows input encounters hang or high memory usage [Fix] Feb 19, 2024 pm 10:48 PM

The Windows input experience is a key system service responsible for processing user input from various human interface devices. It starts automatically at system startup and runs in the background. However, sometimes this service may automatically hang or occupy too much memory, resulting in reduced system performance. Therefore, it is crucial to monitor and manage this process in a timely manner to ensure system efficiency and stability. In this article, we will share how to fix issues where the Windows input experience hangs or causes high memory usage. The Windows Input Experience Service does not have a user interface, but it is closely related to handling basic system tasks and functions related to input devices. Its role is to help the Windows system understand every input entered by the user.

Solve win11 search bar input problem Solve win11 search bar input problem Dec 26, 2023 pm 12:07 PM

The search bar is a very useful function in the win11 system, which can help us find the settings, functions and services we want. However, some friends have encountered the situation where the win11 search bar cannot be entered. We can modify the relevant data in the registry to solve the problem. Let's follow the editor to solve it. What to do if you can’t type in the win11 search bar 1. First, we can press “win+r” on the keyboard to bring up run. 2. Then enter "regedit" and press Enter to open the Registry Editor. 3. Then enter "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Expl" in the path above

How to input word matrix How to input word matrix Mar 19, 2024 pm 11:00 PM

Matrix is ​​a formula we often use and encounter, but do you know how to input a matrix in word? Many people may have never been exposed to it and will feel confused when using it. So, here we will share with you how to input the word matrix. I hope that sharing this technique can bring help and inspiration to you. 1. First, create and open a word document. In order to demonstrate the operation, we will use a blank document for demonstration. As shown in the figure below: 2. If we want to input the matrix, we need to find the [Insert] button in the menu bar. This button can insert many content options, such as pictures, etc., all from this menu bar. 3. After clicking [Insert], look on the right side of our tool options and you can find [Formula], and then we click [

C program to input an array of sequences of integers separated by spaces C program to input an array of sequences of integers separated by spaces Aug 25, 2023 am 11:33 AM

Problem Statement Write a C program that takes space separated integers as array input. SampleExamples input 12345 output ‘Arrayelementsare-’1,2,3,4,5Explanation’s Chinese translation is: The explanation input contains 5 integers separated by spaces. Input 997687542356878967343423 Output ‘Arrayelementsare-’99,76,87,54,23,56,878,967,34,34,23 The Chinese translation of Explanation is: Explanation The input contains 11 integers separated by spaces. Method 1 In this method, we will replace the input with empty

PHP Practice Guide: How to determine if the input contains only numbers and letters PHP Practice Guide: How to determine if the input contains only numbers and letters Mar 28, 2024 pm 03:06 PM

In PHP programming, sometimes we need to limit the data input by the user, such as determining whether the input only contains numbers and letters. This is often encountered in actual project development, so it is very important to master how to implement this function. This article will introduce how to use PHP to determine that the input only contains numbers and letters, and give specific code examples. Why do you need to determine that the input only contains numbers and letters? In website development, the data entered by the user may be used for important functions such as database operations and file operations. If the data entered by the user contains special

Notes and Examples: How to Correctly Enter Floating Point Numbers in Python Notes and Examples: How to Correctly Enter Floating Point Numbers in Python Feb 02, 2024 pm 06:34 PM

Notes and examples of Python floating-point input In Python, floating-point numbers are a common data type used to represent values ​​with decimal parts. When making floating-point input, there are some things we need to know and pay attention to to ensure the correctness and accuracy of the input. This article will introduce several common considerations and provide sample code to deepen understanding. Floating-point input methods In Python, there are many floating-point input methods. The common ones are as follows: Use floating-point numbers directly for input: for example: x

How to input the inequality symbol in PPT How to input the inequality symbol in PPT Mar 26, 2024 pm 03:21 PM

1. Open the PPT software and enter the operation interface. 2. Find the insert option in this interface. 3. Click the Insert option and find the Special Symbol option in its sub-menu. 4. Click the Special Symbol option to pop up the Insert Special Symbol dialog box. 5. Find the mathematical symbol option in this dialog box. 6. Click on the Mathematical Symbol option and find the Not equal to symbol option within it. 7. Click this option and you can see that our inequality symbol has been entered in the input area.

See all articles