Establecer UITextField Longitud máxima [duplicar]


Esta pregunta ya tiene una respuesta aquí:

¿hay alguna manera para establecer la longitud máxima de un UITextField?

Algo así como el atributo MAXLENGTH en los campos de entrada HTML.

Author: typeoneerror, 2010-03-26

11 answers

Esto funciona correctamente con retroceso y copiar y pegar:

#define MAXLENGTH 10

- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    NSUInteger oldLength = [textField.text length];
    NSUInteger replacementLength = [string length];
    NSUInteger rangeLength = range.length;

    NSUInteger newLength = oldLength - rangeLength + replacementLength;

    BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;

    return newLength <= MAXLENGTH || returnKey;
}

UPDATE: Actualizado para aceptar la clave de retorno incluso cuando está en MAXLENGTH. Gracias Sr. Rogers!

 236
Author: Tomas Andrle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-10 15:57:17

UPDATE

No puedo borrar esta respuesta porque es la aceptada, pero no era correcta. Aquí está el código correcto, copiado de TomA a continuación:

#define MAXLENGTH 10

- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    NSUInteger oldLength = [textField.text length];
    NSUInteger replacementLength = [string length];
    NSUInteger rangeLength = range.length;

    NSUInteger newLength = oldLength - rangeLength + replacementLength;

    BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;

    return newLength <= MAXLENGTH || returnKey;
}

ORIGINAL

Creo que te refieres a UITextField. Si es así, entonces hay una manera simple.
  1. Implementar el protocolo UITextFieldDelegate
  2. Implementar el método textField:shouldChangeCharactersInRange:replacementString:.

Ese método se llama en cada toque de carácter o reemplazo de carácter anterior. en este método, puedes hacer algo como esto:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.text length] > MAXLENGTH) {
        textField.text = [textField.text substringToIndex:MAXLENGTH-1];
        return NO;
    }
    return YES;
}
 40
Author: coneybeare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-17 21:41:06

Una mejor función que maneja los espacios atrás correctamente y limita los caracteres al límite de longitud suministrado es la siguiente:

#define MAXLENGTH 8

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        int length = [textField.text length] ;
        if (length >= MAXLENGTH && ![string isEqualToString:@""]) {
            textField.text = [textField.text substringToIndex:MAXLENGTH];
            return NO;
        }
        return YES;
    }

Salud!

 16
Author: Varun Chatterji,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-17 10:46:38

Este código limita el texto mientras que también le permite introducir caracteres o pegar en cualquier lugar en el texto. Si el texto resultante es demasiado largo, cambia los caracteres en el rango y trunca el texto resultante hasta el límite.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSUInteger newLength = [textField.text length] - range.length + [string length];
    if (newLength >= MAXLENGTH) {
        textField.text = [[textField.text stringByReplacingCharactersInRange:range withString:string] substringToIndex:MAXLENGTH];
        return NO;
    }
    return YES;
}
 11
Author: Andy Bradbrook,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-19 21:54:15

Creo que este código haría el truco:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range 
                                                       replacementString:(NSString*)string
{
   if (range.location >= MAX_LENGTH)
      return NO;
    return YES;
}

Con este método delegado puede evitar que el usuario agregue más caracteres que MAX_LENGTH a su campo de texto y se le debe permitir al usuario ingresar espacios atrás si es necesario.

 4
Author: Roberto Miranda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-30 00:08:59

Para mí esto hizo la magia:

if (textField.text.length >= 10 && range.length == 0)
    return NO;
return YES;
 2
Author: vishwa.deepak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-18 13:06:54

Así es como resolví ese problema. Cuando se alcanza el límite máximo, no intentará agregar más... solo podrá eliminar caracteres

#define MAX_SIZE ((int) 5)
...

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.text length] >= MAX_SIZE && ![string isEqualToString:@""]) {
        return NO;
    }

    return YES;
}
 2
Author: pedrotorres,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-03 08:52:00

Creo que no existe tal propiedad.

Pero el texto que se asigna a la etiqueta UILabel tiene que ser un NSString. Y antes de asignar esta cadena a la propiedad text de UILabel, puede usar, por ejemplo, el siguiente método de NSString para recortar la cadena en un índice dado (su longitud máxima):

- (NSString *)substringToIndex:(NSUInteger)anIndex
 1
Author: schaechtele,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-26 13:37:28

Esto es similar a la respuesta de coneybeare, pero ahora el campo de texto puede contener un máximo de símbolos MAXLENGTH:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField.text length] > MAXLENGTH - 1) {
        textField.text = [textField.text substringToIndex:MAXLENGTH];
        return NO;
    }
    return YES;
}
 1
Author: objcdev.ru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-05 17:58:26

Debe tener en cuenta la ubicación en la que se coloca el texto, así como la longitud del texto que se agrega (en caso de que peguen más de un carácter). El patrón entre estos con respecto a la longitud máxima es que su suma nunca debe exceder la longitud máxima.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSInteger locationAndStringLengthSum = range.location + [string length];

    if ([textField isEqual:_expirationMonthField]) {
        if (locationAndStringLengthSum > EXP_MONTH_FIELD_MAX_CHAR_LENGTH) {
            return NO;
        }
    }
    else if ([textField isEqual:_expirationYearField]) {
        if (locationAndStringLengthSum > EXP_YEAR_FIELD_MAX_CHAR_LENGTH) {
            return NO;
        }
    }
    else if ([textField isEqual:_securityCodeField]) {
        if (locationAndStringLengthSum > SECURITY_FIELD_MAX_CHAR_LENGTH) {
            return NO;
        }
    }
    else if ([textField isEqual:_zipCodeField]) {
        if (locationAndStringLengthSum > ZIP_CODE_MAX_CHAR_LENGTH) {
            return NO;
        }
    }

    return YES;
}
 1
Author: David Robles,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-21 20:46:50

Es necesario asignar delegado en ViewDidLoad

TextFieldname.delegate=self
 -3
Author: jjavierfm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-18 16:59:44