简体   繁体   中英

Passing Data Between View Controllers in Swift 4

I've got a login page on the main View Controller which passes a "verified" string to EslViewController , this, I can get to work, but it's now when I want to pass this "verified" to IP_ModuleViewController that I'm having issues with... the code at the moment is;

@IBAction func backButton(_ sender: Any) {
    if installer == "verified"{
        performSegue(withIdentifier: "main/login", sender: self)
    }
        func prepare(for segue: UIStoryboardSegue, sender: Any?){
            let mainController = segue.destination as! ViewController
            mainController.myvar = installer
    }
}

@IBAction func button1(_ sender: Any) {
    if installer == "verified"{
        performSegue(withIdentifier: "Button1", sender: self)
    }
    func prepare(for segue: UIStoryboardSegue, sender: Any?){
        let IPController = segue.destination as! IP_ModuleQuickStartViewController
        IPController.verified = installer
    }
}

Now, my problem is that the func prepare(for segue: UIStoryboardSegue, sender: Any?) isn't running, I realize that this is because it's not an Override Func (I think), but if I have the override func instead I can only see that you can pass data from one? so the second IBAction (button 1) won't work because the Override Func for the back button which goes to ViewController also runs when it's meant to be going to IPcontroller , Any ideas?

Your problem is that your prepare methods never run because you never call them.

Look, when you call performSegue , then prepare(for segue: sender:) is called too, so you can override this method in your ViewController and because you're passing identifier as parameter of performSegue method you can determine what should happen if segue has this or this identifier

So, delete prepare for segue methods from IBActions

@IBAction func backButton(_ sender: Any) {
    if installer == "verified"{
        performSegue(withIdentifier: "main/login", sender: self)
    }
}

@IBAction func button1(_ sender: Any) {
    if installer == "verified"{
        performSegue(withIdentifier: "Button1", sender: self)
    }
}

instead override prepare(for segue: sender:) method of ViewController and inside specify what should happen if segue has "main/login" indentifier or "Button1" :

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "main/login" {
        let mainController = segue.destination as! ViewController
        mainController.myvar = installer
    } else if segue.identifier == "Button1"
        let IPController = segue.destination as! IP_ModuleQuickStartViewController
        IPController.verified = installer
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM