0
votes

I have two UITextfields as follows,

enter image description here

If the user enter 4 digits in the first textfield, then the second textfield should becomesfirstresponder. I have tried below code,

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
  int num = [textField.text length] - range.length;
  if(textField==pin && num ==4)
  {
    [cpin becomeFirstResponder];
  }
}

This works like, the user has to enter the fifth digit. I want the second textfield to becomes responder after entering four digits in the first UITextfield. How to do that?

4
Change the num == 4 to num == 3?CW0007007
@CW0007007, If I make num==3, fourth letter is typed on the cpin.Nazik
Change it to + range.length then 4 should work, you are omiting the newly typed character from the num count. AS the textField text doesn't update until after that method returns.. Also you need to return YES; from that method.CW0007007
@CW0007007, Pl elaborate more.Nazik

4 Answers

4
votes

You need to omit the RANGE parameter..

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
  if([textField.text length] == 3 && ![string isEqualToString:@""]) // Verify that replacementString is a digit and not a backspace
  {
    textField.text = [textField.text stringByAppendingString:string];
    [cpin becomeFirstResponder];
    return NO;
  }

  return YES;
} 
1
votes

Untested as I don't have access to IDE atm

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    int num = [textField.text length] + range.length;
    if(textField==pin && num ==4)
    {
        [cpin becomeFirstResponder];
    }
}

Or i'm sure you could just use int num = string.length or get rid og the int num all together and just use: if (textField == pin && string.length == 4)

0
votes

Try This:

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
          int num = [textField.text length];
          if(textField==pin && num ==4) {
            [cpin becomeFirstResponder];
          }
         return YES;
    }
0
votes

Please try this. this should work

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)strin
{
    int num = [textField.text length] - range.length;
    if(textField== pin && num ==4)
    {
        [cpin becomeFirstResponder];
        return NO;
    }
    return YES;
}

Hope this helps.