Fix maximum character limit in text field
-
19-08-2019 - |
Question
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;
}
OTHER TIPS
To enable user to use backspace, you should use code like this (range.length is only zero when you push backspace):
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 >= 10 && range.length == 0)
return NO;
return YES;
}
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;
}