iphoneuitextfieldbackspace

How can I allow backspace in a UITextField?


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

Solution

  • Try this.

    - (BOOL)textField:(UITextField *)inputTextField shouldChangeCharactersInRange (NSRange)range replacementString:(NSString *)string
    {
       return (textField.text.length >= 5 && range.length == 0) ? NO : YES;
    }