Forum > C++ > How to limit input length of CCTextFieldTTF ?

How to limit input length of CCTextFieldTTF ?

By kdpyung Posted 2012-02-10 09:42 Comments 3
kdpyung
  • Posts: 12

To limit max lengt of CCTexFieldTTF what should I do?

UITextField it done by

Implement the UITextFieldDelegate protocol

  • (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if ([textField.text length] > MAXLENGTH) { textField.text = [textField.text substringToIndex:MAXLENGTH-1]; return NO; } return YES; }

I was try using CCTextFieldDelegate but still work strange when it’s length over MAX_LENGTH.
It seem to not working with IME.

#define MAX_LENGTH = 5;

class UITextFieldDelegate: public CCTextFieldDelegate {
virtual bool onTextFieldInsertText(CCTextFieldTTF * sender, const char * text, int nLen) {
if (_calcCharCount(sender->getString()) > MAX_LENGTH)
return true;

CC_UNUSED_PARAM(sender);
CC_UNUSED_PARAM(text);
CC_UNUSED_PARAM(nLen);
return false;
}
};

Thank you.

sue602
  • Posts: 88

#1 RE: 2012-02-13 01:32

I check it for “number input”,i think it also can be check for input length.

/***
@brief If the sender doesn’t want to insert the text, return true;
**/
bool CCPageIndicator::onTextFieldInsertText(CCTextFieldTTF * sender, const char * text, int nLen)
{
bool isValid = false;
int intValue = atoi(text);
const char * curValueChar = sender->getString();
std::string curValueStr(curValueChar);

if (intValue >=0 && intValue<=9) {
curValueStr.append(text);
int curValue = atoi(curValueStr.c_str());
if (curValue>0 && curValue <= this->getMaxPage())
{
isValid = true;
curPage = curValue;
}
}
return !isValid;
}

kdpyung
  • Posts: 12

#2 RE: 2012-02-13 05:57

It dosen’t work completely.

I was try using CCTextFieldDelegate but still work strange when it’s length over 5.
It seem to not working with IME.

class UITextFieldDelegate: public CCTextFieldDelegate
{
virtual bool onTextFieldInsertText(CCTextFieldTTF * sender, const char * text, int nLen)
{
if (_calcCharCount(sender->getString()) > 5)
return true;

CC_UNUSED_PARAM(sender);
CC_UNUSED_PARAM(text);
CC_UNUSED_PARAM(nLen);
return false;
}
};

neosuram
  • Posts: 1

#3 RE: 2012-12-12 10:20

Ok. I got it.

‘Return’ button on soft keyboard does not mean ‘detachIME’.
It just put ‘’ character.

So I had to check ‘’ character before check the length of sender~~>getString.
if == 0) {
sender~~>detachWithIME();
return true;
}

Loggin to reply

Copyright © 2010 - 2013 Cocos2d-x.orgClustrmaps