Search code examples
iphoneiosuitextfielduitextfielddelegate

How to get second uitextfield calculated automatically after finishing typing in first uitextfield


I have 2 uitextfields (dollarPayTextField and rielPayTexField). After finishing typing in dollarPayTextField, I want rielPayTextField calculated automatically.

For example, total: 10 $, when I type in 9 $ in dollarPayTextField, I want rielPayTextField showing 4000. Thus, how I can do that ? This is my code for calculating the remain:

-(void)updateChangeRemainInriel{
    double dollarPay = [self.dollarPayTextField.text doubleValue];
    double dollarRemain = [self.abill getTotalPrice] - dollarPay;
    NSLog(@"%.2f",[self.dollarPayTextField.text doubleValue]);
    self.rielPayTextField.text =  [NSString stringWithFormat:@"%.2f",dollarRemain * self.anExchangeRate.rielBuyPerDollar];
}

Solution

  • Hope you added UITextFieldDelegate in your .h file and your_textField.delegate=self; in your .m file. If you use this, it calculates every time the input is changed

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
       [textField addTarget:self action:@selector(yourTextFieldChanged:) forControlEvents:UIControlEventEditingChanged];  
    
        return YES;
    }
    
    - (void)yourTextFieldChanged:(UITextField *)textField
    {
       double dollarPay = [self.dollarPayTextField.text doubleValue];
       double dollarRemain = [self.abill getTotalPrice] - dollarPay;
       NSLog(@"%.2f",[self.dollarPayTextField.text doubleValue]);
       self.rielPayTextField.text =  [NSString stringWithFormat:@"%.2f",dollarRemain *    self.anExchangeRate.rielBuyPerDollar];
    }
    

    if you use this, it calculates after you finish entering the value

    -(void)textFieldDidEndEditing:(UITextField *)textField{
       double dollarPay = [self.dollarPayTextField.text doubleValue];
       double dollarRemain = [self.abill getTotalPrice] - dollarPay;
       NSLog(@"%.2f",[self.dollarPayTextField.text doubleValue]);
       self.rielPayTextField.text =  [NSString stringWithFormat:@"%.2f",dollarRemain *    self.anExchangeRate.rielBuyPerDollar];
    }