Search code examples
swiftsegueuistoryboardsegue

How to pass two textfield entries to another ViewController with using segue


I want my user to go to the TableViewController once they enter their "id" and "password" but when we use prepare and performsegue methods we just send one variable.

@IBAction func logIn(_ sender: Any) {
    performSegue(withIdentifier: "emailSegue", sender: emailTextField.text)
    performSegue(withIdentifier: "passwordSegue", sender: passwordTextField.text)
}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let guest = segue.destination as! ExpenseTableViewController

    guest.incoming.append(sender as! String)
}

As you can see here I want to perform two different segues and I have also created two segues on the storyboard from ViewController to tableview controller named as "emailSegue" and "passwordSegue", but in the prepare function I can only prepare for the one of them which is the "emailSegue" when I run the code, it does compile and I can append email to the array but not my password.

So I wonder how I can get them both to be sent? Is there a way to prepare for 2 different segues? Could not find an example of it on anywhere else.

Thanks in advance.


Solution

  • You can only perform one segue, but you can send multiple parameters.

    Just pass an array rather than a single string:

    @IBAction func logIn(_ sender: Any) {
       performSegue(withIdentifier: "emailSegue", 
                    sender: [emailTextField.text!, passwordTextField.text!])
    }
    

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "emailSegue" {
           let guest = segue.destination as! ExpenseTableViewController
           guest.incoming.append(contentsOf: sender as! [String])
        }
    }
    

    PS: Rather than forced unwrapping the text properties you should validate them:

    @IBAction func logIn(_ sender: Any) {
       guard let email = emailTextField.text, !email.isEmpty,
             let password = passwordTextField.text, !password.isEmpty else {
          // show an alert
          return 
       }
       performSegue(withIdentifier: "emailSegue", sender: [email, password])
    }