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
2009-01-23 07:45:16
Its working .... thanks for ur answer.....
Nahid
2009-01-23 09:11:13
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
2009-07-17 04:28:51
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
2009-07-17 04:34:56
Thanks. I changed it.
Brad Smith
2009-07-17 05:10:58
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
2009-07-17 04:37:05
A:
Ilya Dyachenko
2009-08-19 06:02:34