Set UITextField Maximum Length

IphoneUitextfieldMax

Iphone Problem Overview


Is there any way to set the maximum length on a UITextField?

Something like the MAXLENGTH attribute in HTML input fields.

Iphone Solutions


Solution 1 - Iphone

This works correctly with backspace and copy & paste:

#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: Updated to accept the return key even when at MAXLENGTH. Thanks Mr Rogers!

Solution 2 - Iphone

UPDATE

I cannot delete this answer because it is the accepted one, but it was not correct. Here is the correct code, copied from TomA below:

#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

I think you mean UITextField. If yes, then there is a simple way.

  1. Implement the UITextFieldDelegate protocol
  2. Implement the textField:shouldChangeCharactersInRange:replacementString: method.

That method gets called on every character tap or previous character replacement. in this method, you can do something like this:

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

Solution 3 - Iphone

A better function which handles backspaces correctly and limits the characters to the supplied length limit is the following:

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

Cheers!

Solution 4 - Iphone

This code limits the text while also allowing you enter characters or paste anywhere into the text. If the resulting text would be too long it changes the characters in the range and truncates the resulting text to the limit.

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

Solution 5 - Iphone

I think this code would do the trick:

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

With this delegate method you can prevent the user to add more characters than MAX_LENGTH to your text field and the user should be allowed to enter backspaces if needed.

Solution 6 - Iphone

For me this did the magic:

if (textField.text.length >= 10 && range.length == 0)
    return NO;
return YES;

Solution 7 - Iphone

this is how i resolved that problem. When max limit is reached it wont try to add more... you will only be able to remove chars

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

Solution 8 - Iphone

I think there's no such property.

But the text you assign to the UILabel has to be an NSString. And before you assign this string to the UILabel's text property you can for example use the following method of NSString to crop the string at a given index (your maxlength):

- (NSString *)substringToIndex:(NSUInteger)anIndex

Solution 9 - Iphone

This is similar to coneybeare's answer, but now the text field can contain a maximum of MAXLENGTH symbols:

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

Solution 10 - Iphone

You have to be aware of the location the text is placed in as well as the length of text being added (in case they're pasting more than one character). The pattern between these with respect to max length is that their sum should never exceed the max length.

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

Solution 11 - Iphone

You need to assign delegate on ViewDidLoad

TextFieldname.delegate=self

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionElegyaView Question on Stackoverflow
Solution 1 - IphoneTomas AndrleView Answer on Stackoverflow
Solution 2 - IphoneconeybeareView Answer on Stackoverflow
Solution 3 - IphoneVarun ChatterjiView Answer on Stackoverflow
Solution 4 - IphoneAndy BradbrookView Answer on Stackoverflow
Solution 5 - IphoneRoberto MirandaView Answer on Stackoverflow
Solution 6 - Iphonevishwa.deepakView Answer on Stackoverflow
Solution 7 - IphonepedrotorresView Answer on Stackoverflow
Solution 8 - IphoneschaechteleView Answer on Stackoverflow
Solution 9 - Iphoneobjcdev.ruView Answer on Stackoverflow
Solution 10 - IphoneDavid RoblesView Answer on Stackoverflow
Solution 11 - IphonejjavierfmView Answer on Stackoverflow