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

痞子三分冷 提交于 2019-12-25 14:45:46

问题


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.


回答1:


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])
}



回答2:


You can only perform one segue at a time, so call performSegue only once when you want the transition to happen and set the two variables in prepareForSegue for the destination view controller. It's best to check what type of segue should be prepared by checking segue.identifier property.



来源:https://stackoverflow.com/questions/47241519/how-to-pass-two-textfield-entries-to-another-viewcontroller-with-using-segue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!