TextField * textField = TextField::create("input words here", "Arial", 30);
textField->setPosition(Vec2(widgetSize.width / 2.0f, widgetSize.height / 2.0f));
textField->addEventListener(CC_CALLBACK_2(HelloWorld::textFieldEvent, this));
void HelloWorld::textFieldEvent(Ref * pSender, TextField::EventType type)
{
switch (type)
{
case TextField::EventType::ATTACH_WITH_IME:
{
TextField * textField = dynamic_cast<TextField*>(pSender);
Size screenSize = CCDirector::getInstance()->getWinSize();
textField->runAction(CCMoveTo::create(0.225f, Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f +textField->getContentSize().height / 2.0f)));
_displayValueLabel->setString(String::createWithFormat("attach with IME")->getCString());
textField->setMaxLengthEnabled(true); //设置允许最大数目限制
textField->setMaxLength(3);
//设置最大允许数目为3
textField->setPasswordEnabled(true);
//设置可设置为密码模式
textField->setPasswordStyleText("*");
//设置密码的遮挡字符为*
textField->setPlaceHolder("input text here");
//设置占位符
textField->setPlaceHolderColor(Color4B::GREEN); //设置占位符颜色
textField->setTextColor(Color4B::RED);
//如果要设置自动换行
textField->ignoreContentAdaptWithSize(false);
//(必须要有的代码)此处为false,如果为true, 则不管setContentSize为何大小,该控件只使用getVirtualRendererSize()这个函数返回的Size大小
((Label*)(textField->getVirtualRenderer()))->setLineBreakWithoutSpace(true);
///(必须要走的最关键代码)
textField->setContentSize(Size(240, 170));
//(必须要有的代码)
textField->setTextHorizontalAlignment(TextHAlignment::LEFT);
//设置文字在水平方向的对齐方式
textField->setTextVerticalAlignment(TextVAlignment::TOP);
//设置文字在垂直方向的对齐方式
//对齐方式setTextHorizontalAlignment我们可以这么理解,LEFT就是整行文字靠着左边对齐,RIGHT就是整行文字靠着右边对齐,
//对齐方式setTextVerticalAlignment我们可以这么理解,TOP就是你整篇文字靠着顶部对齐,反之BOTTOM就是整篇文字靠着底部对齐
textField->getVirtualRendererSize();
//可以获取它的实际大小
((Label*)(textField->getVirtualRenderer()))->setLineBreakWithoutSpace(true);
//为true,内容超过width,会自动换行
}
break;
case TextField::EventType::DETACH_WITH_IME:
{
TextField * textField = dynamic_cast<TextField*>(pSender);
Size screenSize = CCDirector::getInstance()->getWInSize();
textField->runAction(CCMoveTo::create(0.225f, Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f));
}
break;
case TextField::EventType::INSERT_TEXT:
break;
case TextField::EventType::DELETE_BACKWARD:
break;
}