How to pass the value of a variable through a button to another class in Swift

Asked

Viewed 514 times

0

I have a login screen, with the e-mail and password fields. I need to use in another viewController the email that was used to log in to the system. But I cannot pass the e-mail typed in viewController Login to another viewController.

  • Are you using storyboard? If yes: http://stackoverflow.com/questions/11577484/passing-variables-between-view-controllers

  • Use the Prepareforsegue method

2 answers

2

If you are using Segues, just overwrite the method prepare in his Viewcontroller login.

For example, assuming the next Viewcontroller be called Nextviewcontroller and the ID of your Follow is Gotonextsegue, the code would look like this:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "GoToNextSegue" {
        let vc = segue.destinationViewController as! NextViewController
        vc.email = "aqui você informa o e-mail"
    }
}

Obviously, in your class Nextviewcontroller you need to have a parameter called email who will receive the information.

1

If you do not use follow, you can pass the following way

First on VC-B declare the variable that will receive the value.

//VC-B 
class VC_B: UIViewController{
    var Valor:String!

    override func viewDidLoad() {
        super.viewDidLoad()

        print(Valor)
    }
}

//VC_A
class VC_A: UIViewController{

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func AbrirVC_B(sender:UIButton){
       let story = UIStoryboard(name: "Main", bundle: nil)
        let vc:VC_B = story.instantiateViewControllerWithIdentifier("VC_B") as! VC_B
        vc.Valor = "Novo Valor"
        self.presentViewController(vc, animated: false, completion: nil)
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.