Search code examples
iosswiftaddtarget

How do I update textfield2 based on editing textfield1?


I like to update textfield2 as soon as totalAmount has been edited, I am trying the following:

    totalAmount.addTarget(self, action: "changeTextField2:", forControlEvents: UIControlEvents.EditingDidEndOnExit)

 func changeTextField2(textField: UITextField) {
        print("Total amount: \(totalAmount.text)")
        //amount vat - calculate vat based on textField
        amountVAT.text = "88"
    }

And i am saving the text field values with

func newItem(){

    let context = self.context
    let ent = NSEntityDescription.entityForName("List", inManagedObjectContext: context)


    let nItem = List(entity: ent!, insertIntoManagedObjectContext: context)
    let numberFormatter = NSNumberFormatter()

    nItem.amountVAT = numberFormatter.numberFromString(amountVAT.text!)
    .....more values
    nItem.invoiceImage = UIImagePNGRepresentation(imageHolder.image!)

    do {
     try context.save()
    } catch {
        print(error)
    }
}
func saveValues(sender: AnyObject) {

        if nItem != nil {
            editItem()
        } else {
            newItem()
        }

        dismissVC()
    }

Solution

  • This can be done using UITextFieldDelegate Method use this function 1.)

    textField1.delegate = self
    

    2.)

    func textFieldDidEndEditing(textField: UITextField)
    {
       if textField == textField1
       {
          textField2.text = textField1.text
       }
    }
    

    now its upto you how you change the totalAmount.