我正在尝试将一些数据从一个视图控制器发送到另一个视图控制器。但我似乎无法使这些代码正常工作!它应该将标签更改为传递给它的变量,但它不会改变任何内容。
ViewController.swift
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SVCSegue" {
let controller = segue.destination as! SecondViewController
if let user = FIRAuth.auth()?.currentUser {
controller.email = user.email
}
}
}
SecondViewController.swift
@IBOutlet weak var usernameLabel: UILabel!
var email:String!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.usernameLabel.text = self.email
}
编辑我还有override func prepare
@IBAction func loginAction(_ sender: Any) {
if self.emailField.text == "" || self.passwordField.text == "" {
let alertController = UIAlertController(title: "Oops!", message: "Please put in an email and password.", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
} else {
FIRAuth.auth()?.signIn(withEmail: self.emailField.text!, password: self.passwordField.text!, completion: { (user, error) in
if error == nil {
self.emailField.text = ""
self.passwordField.text = ""
} else {
let alertController = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
}
})
}
}
答案 0 :(得分:0)
我不确定,但是根据在seque期间调用SecondViewController的不同生命周期函数的时间,可能在执行准备代码之前调用了viewDidLoad。
尝试为电子邮件提供默认值,以便您可以使用该值。另外,在prepare方法的else部分中将电子邮件值设置为其他值,以查看if条件是否失败。
答案 1 :(得分:0)
@IBAction func loginAction(_ sender: Any) {
if self.emailField.text == "" || self.passwordField.text == "" {
let alertController = UIAlertController(title: "Oops!", message: "Please put in an email and password.", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
} else {
FIRAuth.auth()?.signIn(withEmail: self.emailField.text!, password: self.passwordField.text!, completion: { (user, error) in
if error == nil {
let sb = UIStoryboard(name: "StoryBoardName", bundle: nil)
let secVC = sb.instantiateViewController(withIdentifier: "ViewControllerIdentifier") as! SecondViewController
if let userValue = FIRAuth.auth()?.currentUser {
secVC.email = userValue.email!
}
self.navigationController?.pushViewController(secVC, animated: true)
} else {
let alertController = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
}
})
}
}
I have made change in loginAction() that is navigate to SecondViewController and pass data of user
Try above code , Hope this help you and solved your issue.