Pregunta

¿Cómo se puede imponer un límite de caracteres fijo en un campo de texto en Cocos2d?

¿Fue útil?

Solución

Para corregir el número máximo de caracteres en un UITextField, puede implementar el Método de delegado UITextField textField: shouldChangeCharactersInRange para devolver false si el usuario intenta editar la cadena más allá de la longitud fija.

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

Otros consejos

Para permitir que el usuario use el espacio de retroceso, debe usar un código como este (range.length es solo cero cuando presiona el espacio de retroceso):


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

El ejemplo anterior solo funciona si el usuario está editando al final del campo de texto (último carácter). Para verificar la longitud real (independientemente de dónde esté editando el usuario, la posición del cursor) del texto de entrada, use esto:

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; 
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top