views:

955

answers:

3

how can fixed maximum character of a text field in cocos2d ?

+2  A: 

To fix the maximum number of characters in a UITextField, you could do implement the UITextField Delegate Method textField:shouldChangeCharactersInRange to return false if the user tries to edit the string past the fixed length.

//Assume myTextField is a UITextField
myTextField.delegate = self;

//implement this UITextFiledDelegate Protocol method in the same class
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.text length] > kMaxTextFieldStringLength)
        return NO;
    else
        return YES; 
}
Brad Smith
Its working .... thanks for ur answer.....
Nahid
Does it still work if I input the max length and then I position myself at the beginning of the text field and I continue typing?
nicktmro
I just tested and it fails if the user resumes editing at the beginning of the text field. Rather than testing if (range.location > kMaxTextFieldStringLength)I would suggest you do a: if ([textField.text length] > kMaxTextFieldStringLength)On another note the range is 0 based.
nicktmro
Thanks. I changed it.
Brad Smith
A: 

The example above only works if the user is editing at the end of the text field (last character). For checking against the actual length (regardless of where the user is editing- cursor position) of the input text use this:

myTextField.delegate = self;

//implement this UITextFiledDelegate Protocol method in the same class
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (range.location > kMaxTextFieldStringLength)
        return NO;
    else
        return YES; 
}
nicktmro
A: 
Ilya Dyachenko