Search code examples
objective-ccocos2d-iphone

Fix maximum character limit in text field


How can a fixed character limit be imposed on a text field in Cocos2d?


Solution

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