Search code examples
iosuitextfielduitextfielddelegate

Unable to edit UITextField after user has entered value in iOS


I have the following implementation of the delegate method in iOS:

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

if (textField.tag == 2){

        if(textField.text.length > 2) {

            return NO;

        }

        return YES;

    }

    else if (textField.tag == 3) {

        if(textField.text.length > 1) {

            return NO;

        }

}

The code is making the necessary restrictions to the user as far as the number of characters that they can enter. However, the textfield is also not allowing the user to edit the text once it has been entered. It doesn't allow any keystrokes (including the delete/backspace key). Is there a way to rectify this to maintain the text length restriction, but allow this value to be edited by the user?


Solution

  • Your checks are all wrong. You don't want to check the length of the current text, you want to check the length of what the text would be if the change was allowed.

    Try this:

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
        NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
        if (textField.tag == 2) {
            return newText.length <= 2; // only allow 2 or less characters
        } else if (textField.tag == 3) {
            return newText.length <= 1; // only allow 1 or less characters
        } else {
            return YES;
        }
    }