Question: I am in a situation here, I've two edit text in a fragment, on back press the value of first edit text is getting replaced by second edit text. Now both the edit text are having same values.

```
<EditText
    android:id="@+id/edit_text"
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:layout_marginTop="20dp"
    android:hint="hint" />

```

Above is my `EditText`, this EditText is inside a layout and I've included the layout in my fragment two times to get the `EditText`, on click of submit I replace this fragment with another one but on backpress when I come back to this fragment, the value of first edit box is getting replaced by second one. Now both has same values.

This is how I am replacing fragment.

```
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.layout_fragment, fragment, tag);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commitAllowingStateLoss();
getSupportFragmentManager().executePendingTransactions();

```

Answer: 
**METHOD 1.** First of all, add this in `viewDidLoad()`:

```
yourTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) // make sure it is the desired textField

```

Then add your function:

```
func textFieldDidChange(_ textField: UITextField) {
    if textField.text!.characters.count  == 4{
         let yourNewViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "yourNewViewControllerIdentifier")
         self.present(yourNewViewController, animated: true, completion: nil)
    }
}

```

---

**METHOD 2.** 

**Step 1:** Conforming to `UITextFieldDelegate`:

```
class yourClass: UIViewController, UITextFieldDelegate{ //... 
}

```

and in viewDidLoad():

```
yourTextField.delegate = self

```

**Step 2:**

Implementing this:

```
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange,replacementString string: String) -> Bool
{
    if textField == yourTextField{ 
        if string.characters.count == 4{
             let yourNewViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "yourNewViewControllerIdentifier")
             self.present(yourNewViewController, animated: true, completion: nil)        

        }

    }
    else{
        // the other textfields
    }

      return true
}

```
Modify your code to :

```
func textFieldDidChange(textField: UITextField){

    print("Text changed: " + textField.text!)
    if(textField.Text.characters.count >3 ) {
    textField.resignFirstResponder()
    let secondViewController =    self.storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as SecondViewController
    self.navigationController.pushViewController(secondViewController, animated: true)
    }
}

```