3

I am new to iOS. I have a viewcontroller for registration, it contains three UITextfields for Email,password, Confirm password and a UIButton. I have some validations, On success of those validation I have to enable signup button. I have implemented it through shouldChangeCharactersInRange, But it returns me old characters e.g.

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

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

It is not getting the textfield value dynamically I think ? or ?

Help me to get out of this.

Muhammad Burhan
  • 145
  • 1
  • 2
  • 11

4 Answers4

1

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];
    }
}
l0gg3r
  • 8,864
  • 3
  • 26
  • 46
1

if you want to get update text, you have to add one line in shouldChangeCharactersInRange method, in that tempStr will print your updated text

- (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;
}
Anjaneyulu Battula
  • 1,910
  • 16
  • 33
0
-(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". So when this method ist called, the textfields content is not updated yet but you can decide if the next change should happen.

Claus

l0gg3r
  • 8,864
  • 3
  • 26
  • 46
Thallius
  • 2,482
  • 2
  • 18
  • 36
0

You need to first append the new string in 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;
}
Hemant Chittora
  • 3,152
  • 3
  • 19
  • 25