Fixar limite máximo de caracteres no campo de texto
-
19-08-2019 - |
Pergunta
Como pode um limite de caracteres fixo ser imposta a um campo de texto no Cocos2d?
Solução
Para fixar o número máximo de caracteres em um UITextField, você poderia fazer implementar o textField:shouldChangeCharactersInRange
UITextField Método Delegado para retornar false se o usuário tentar editar a corda após o comprimento fixo.
//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;
}
Outras dicas
Para permitir ao utilizador o uso de retrocesso, você deve usar um código como este (range.length só é zero quando você empurra 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;
}
O exemplo acima só funciona se o usuário está editando no final do campo de texto (último caractere). Para verificação contra o comprimento real (independentemente de onde o usuário é a posição do cursor Edição-) do uso de entrada de texto seguinte:
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;
}