Search code examples
swiftnotificationsuitextfieldlistenerobservers

Auto update UITextfield with data from separate UITextfield


I have three UITextfields (customerRequestTextField , fundsAvailableTextField and amountOwedMarketTextField) on the same ViewController.

I would like to set up the amountOwedTextField so that it automatically updates its field by subtracting the data entered into the other two textfields (customerRequestTextField - fundsAvailableTextField).

Should I use NSNotifications? Or a selector? Or something else?

I have tried setting up a selector, but my version does not work.

This is declared globally.


var amountOwedToMarket

This code is located in the viewDidLoad().

amountOwedMarketTextField.text = String(amountOwedToMarket)

        amountOwedMarketTextField.addTarget(self, action: #selector(self.textFieldDidChange(sender:)), for: .editingChanged)

    }

This is declared outside of the viewDidLoad()

    @objc func textFieldDidChange(sender: UITextField) -> Int {

        return Int(amountCustomerRequestTextField.text!) ?? 21

    }

Solution

  • You need to add the target to textfields that you want to listen to their changes

    // in viewDidLoad
    amountCustomerRequestTextField.addTarget(self, action: #selector(self.textFieldDidChange), for: .editingChanged)  
    fundsAvailableTextField.addTarget(self, action: #selector(self.textFieldDidChange), for: .editingChanged)
    

    @objc func textFieldDidChange(_ sender: UITextField) {  
       if let first =  Int(amountCustomerRequestTextField.text!) , let second = Int(fundsAvailableTextField.text!) { 
            amountOwedMarketTextField.text = "\(first - second)" 
       }
    }