Pergunta

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?

Foi útil?

Solução

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

Outras dicas

use below code

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
       NSUInteger newLength = [textField.text length] + [string length] - range.length;
       if (textField.tag == 2)
       {           
            if (newLength>2) {
            //     [textField resignFirstResponder];
                   return NO;
             }
             else {
                   return YES;
             }
        }
        else if (textField.tag == 3)
        {
            if (newLength>1) {
            //     [textField resignFirstResponder];
                   return NO;
             }
             else {
                   return YES;
             }
        }
}

try this you will be succeed

I'm using userInteractionEnabled property of UITextField to enable and disable editting. Not sure if you are looking for it.

    if () // Editable
    {
        textField.userInteractionEnabled = YES;
    }
    else // Non Editable
    {
        textField.userInteractionEnabled = NO;
    }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top