Richard Downs Richard Downs - 1 month ago 7
iOS Question

Finishing this snippet of code to pass data via a segue from one controller to another

I have a ViewController, "ViewController".

Within this view there is an attribute 'userEmailText.text' that I want to pass along to another view controller, "CreateNewCommunity"

I have a button connected to a segue with identifier 'createCommunitySegue'. I have create the code for when this is tapped:

@IBAction func createCommunityTapped(_ sender: AnyObject) {
self.performSegue(withIdentifier: "createCommunitySegue", sender: self)
}


In my second view controller, "CreateNewCommunity" I have a variable:

var myEmail: String?


and I have started to build the code ready to receive the data from the segue:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "createCommunitySegue" {
let createCommunityController: CreateNewCommunity = segue.destination as! CreateNewCommunity
createCommunityController.myEmail =
}

}


How do I finish this set-up so that the initial 'userEmailText.text' value is passed by "ViewController" through segue 'createCommunitySegue' into "CreateNewCommunity" view controller?

Thanks

Answer

Why not just

createCommunityController.myEmail = userEmailText.text

I think your problem is that you have a wrong idea of how to pass data from one vc to another.

The VC that you are passing data to doesn't recieve the data. It is the VC that has the data proactively pass the data to the VC that needs it.

My guess would be that you put this code

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "createCommunitySegue" {
        let createCommunityController: CreateNewCommunity = segue.destination as! CreateNewCommunity
        createCommunityController.myEmail =
    }

}

in the CreateNewCommunity controller! You should instead put the above in ViewController not CreateNewCommunity , and write

createCommunityController.myEmail = userEmailText.text

it should work.