2

In my project, I have to limit the length of a UITextField to 6 characters. This is working absolutely fine. Once I end editing and start editing again and I click backspace my application crashes.

Here is the code:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{   
    NSUInteger newLength = [txtLicense.text length] + [strNumber length] - range.length;
    return (newLength > 6) ? NO : YES;
}
etolstoy
  • 1,798
  • 21
  • 33
Baby Groot
  • 4,637
  • 39
  • 52
  • 71

4 Answers4

5

Try this.

- (BOOL)textField:(UITextField *)inputTextField shouldChangeCharactersInRange (NSRange)range replacementString:(NSString *)string
{
   return (textField.text.length >= 5 && range.length == 0) ? NO : YES;
}
iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
Rakesh Bhatt
  • 4,606
  • 3
  • 25
  • 38
2

Implement your delegate method as follows –

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range
                                                                    withString:string];

    return ([toBeString length] > 6) ? NO : YES;
}

We will get what the resultant string will be and check its length. This way backspaces would work.

Deepak Danduprolu
  • 44,595
  • 12
  • 101
  • 105
1

If you want to achieve maximum length validation in UITextField you can use following working code from one of my working project.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
    if ([textField.text length] > 6) {
        textField.text = [textField.text substringToIndex:6];
        return NO;
    }
    return YES;
}
Janak Nirmal
  • 22,706
  • 18
  • 63
  • 99
0

I am not sure what you want to achieve here, well you can try this one:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
 if (string && [string length] && [textField.text length] <= 6) {
 return NO;
 }
 
 return YES;
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Manoj
  • 953
  • 2
  • 8
  • 24