ShouldChangeCharactersInRange returns old iOS results

I am new to iOS. I have a viewcontroller for registration, it contains three UITextfields for email, password, confirmation password and UIButton. I have multiple validations. Upon successful testing, I have to enable the register button. I have implemented it via shouldChangeCharactersInRange , but it gives me back old characters for example.

I type a => It returns me ""
then 
I type ab => It returns a
then 
I remove b => It returns me ab

      

In reality it is:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range  replacementString:(NSString *)string {
if ([textField.text length]>0) {
  [self enableSignUpButton];
}
   return YES;
}


-(void)enableSignUpButton {
if ([emailTextField.text length]>0 && [passwordTextfield.text length]>0 &&  [confirmPasswordTextfield.text length]>0)
        signUpButton.enabled=TRUE;
        return;
}
signUpButton.enabled=FALSE;
}

      

I don't think the dynamic value of the textbox is I think? or?

Help me get out of this.

+3


source to share


4 answers


Handle text change event like this



- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.textField addTarget:self 
                       action:@selector(textFieldDidChange:) 
             forControlEvents:UIControlEventEditingChanged];  
}

- (void)textFieldDidChange:(UITextField *)aTextField
{
    if ([textField.text length]>0)
    {
       [self enableSignUpButton];
    } else {
       // NOTE
       [self disableSignupButton];
    }
}

      

+1


source


if you want to get the update text you need to add one line to the shouldChangeCharactersInRange method , your updated text will be printed to tempStr



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

    NSString *tempStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSLog(@"updated Text: %@",tempStr);
    if ([tempStr length] > 0) {
        [self enableSignUpButton];
    }

    return YES;
}

      

+1


source


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

      

take a look at the name of this method. It is called "shouldChange", not "hasChanged". Therefore, when this method is called, the contents of the text boxes are not yet updated, but you can decide if the next change occurs.

Claus

0


source


You need to first add a new line to the existing text and then compare the length

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    if (newLength>0) {
       [self enableSignUpButton];
    }
   return YES;
}

      

0


source







All Articles