Pregunta

I have three types of text fields. in that I need only minimum numbers only . below code I write-in but its not working. help me

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ 
    if (country.text.length <= 4) {
        return YES;
    }

    if(code.text.length<=4 ) {
        return YES;
    }

    if(textPhone.text.length<=10) {
        return YES;
    }

    return YES;
}
¿Fue útil?

Solución

Your logic is flawed here. You don't even base your checks on which field is edited.

Try this:

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

    // Allow backspace anyway
    if (range.length == 0)
        return YES;

    if (textField == country)
        return (country.text.length <= 4);

    else if (textField == code)
        return (code.text.length <= 4);

    else if (textField == textPhone)
        return (textPhone.text.length <= 10);

    // Default for all other fields
    return YES;
}

Otros consejos

First off this seems absolutely pointless since you return YES in every case so why even bother with the if statement but if you insist on doing it try any of the below.

After you have initialized your UITextFields set the following

... Initilization code for country, textPhone and code.
[country setTag:1001];
[code setTag:1002];
[textPhone setTag:1003];

and in your shouldChangeCharactersInRange: method do

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ 
    switch([textField tag]) {
        case 1001:
                  // Do whatever 
                  return (textField.text.length <= 4);
        case 1002:
                  // Do whatever
                  return (textField.text.length <= 4);
        case 1003:
                  // Do whatever
                  return (textField.text.length <= 10);
        default:
                return YES;
    }
}

Are if you want to do it with an if statement still try

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ 
    if((([textField tag] == 1001 || [textField tag] == 1002) && [textField text].length <= 4) || ([textField tag] == 1003 && [textField text].length <= 10)) {
        return ((([textField tag] == 1001 || [textField tag] == 1002) && [textField text].length <= 4) || ([textField tag] == 1003 && [textField text].length <= 10));
    }
    return YES;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top