How to limit input length of CCTextFieldTTF ?

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.

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;
}

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;
}
};

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;
}