【熟悉引擎第七步】Label与TextField

前言,送给自己,我之前因为期末考试开始停更了,复习很好,考得也很好,现在我要继续了,喜欢编程,这是给自己一个叛逆的青春,今天,我坐在宿舍,旁边有打机,有看电视的,有说话的,而我,听着音乐,码着代码,如果五年后,我要坐在牛逼的办公楼里,或者开着自己的公司,有着庞大的业务,那么我今天就要非常努力!我每天都要非常努力!加油!

Label的使用,如果对于LabelTTF不熟悉,可以追到里面查看定义。

然后在TextFieldTTF.cpp中添加下面的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}

Size size = Director::getInstance()->getVisibleSize();
LabelTTF*label = LabelTTF::create();
label->setString("Today is a sunny day!");
label->setFontSize(36);
label->setPosition(size.width / 2,size.height / 2);
addChild(label);
return true;

程序执行结果:

}




CCTextFieldTTF是一个显示文本控件的类用于输入文本和现实文本类似于Windows编程中的Static控件和Edit控件。


程序实例:使用TextFieldTTF类创建一个文本,触摸文本弹出软键盘,并且可以通过软键盘向TextFieldTTF中输入文字

首先创建一个TextFieldTTF.h的头文件,在头文件添加下面的代码

18
19
20
21
22
23
#ifndef__TextFieldTTF_H__
#define__TextFieldTTF_H__
#include"cocos2d.h"
USING_NS_CC;
class TextFieldTTF: public cclayer
{
:
bool init();
static CCScene*scene();
//用于处理触摸事件
ccTouchBegan(CCTouch*,CCEvent*);
//用于在程序中创建一个文本控件
CCTextFieldTTF*textEdit;
CREATE_FUNC(TextFieldTTF);
};
#endif//__HELLOWORLD_SCENE_H__

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
#include"TextFieldTTF.h"
CCScene*TextFieldTTF::scene()
{
CCScene*scene=CCScene::create();
TextFieldTTF*layer=TextFieldTTF::create();
scene->addChild(layer);
return scene;
}
TextFieldTTF::init()
{
//初始化父类
cclayer::init();
//得到窗口的尺寸
CCSizewinSize=CCDirector::sharedDirector()->getWinSize();
//创建文本框
//第一个参数:文本框中显示内容
//第二个参数:字体
//第三个参数:文本的大小
textEdit=CCTextFieldTTF::textFieldWithPlaceHolder( "Pleaseinputyourname:" ,
"Arial" ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.1em!important; margin:0px!important; outline:0px!important; overflow:visible!important; padding:0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,36);
//设置文本框的位置
textEdit->setPosition(ccp(winSize.width/2,winSize.height/2));
//添加文本框到层上
addChild(textEdit);
//当触摸到控件的时候弹出软键盘
setTouchMode(kCCtouchesOneByOne);
setTouchEnabled( true );
return ;
}
TextFieldTTF::ccTouchBegan(CCTouch*touch,CCEvent*ev)
{
//用于判断是否点中了控件
isClicked=textEdit->boundingBox().containsPoint(touch->getLocation());
//如果点中了控件
if (isClicked)
{
//弹出软键盘
textEdit->attachWithIME();
}
//表示接受触摸消息
;
}

程序执行结果:

在Windows下单击“Please input your name: ”会没有反应,因为Windows下没有软键盘

程序移值到Android下的执行结果:

触摸“Please input your name :”后弹出软键盘

使用软键盘输入一段文字后:

选择完成后文字显示在控件上

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...