Chino Pan Chino Pan - 1 month ago 7
Swift Question

Pass data with prepareForSegue

Im trying to pass data from viewController 1 to viewController2, I have 2 buttons and 1 segue(therefore there is one segue identifier) for those 2 buttons, each button when pressed should show: 1 label to show the title and 1 textView to show a definition, I am having troubles to show its own data of each word; I know it has to be the some code referencing the SENDER in the performSegueWithIdentifier, but I don't know how to do it.

I appreciate your help !!! thanks.

here is my code

class ViewController: UIViewController {

@IBAction func AbstractionBtn(sender: AnyObject) {
performSegueWithIdentifier("ShowDefinition", sender: "Abstraction")
}

@IBAction func binarySystemBtn(sender: AnyObject) {
performSegueWithIdentifier("ShowDefinition", sender: "Binary System")

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "ShowDefinition") {
if let destinationViewController = segue.destinationViewController as? EnglishViewController {
destinationViewController.titleMsg = "Abstraction"
destinationViewController.definitionMsg = "Abstraction Definition"
}
} else if(segue.identifier == "ShowDefinition"){if let destinationViewController = segue.destinationViewController as? EnglishViewController {
destinationViewController.titleMsg = "Binary System"
destinationViewController.definitionMsg = "Binary System Definition"
}
}
}

Answer

You have correctly passed the definition as a String in the sender parameter in performSegueWithIdentifier. You just need to use its value in prepareForSegue, but first you must cast it from AnyObject? back to a String.

Your code could be something like:

class ViewController: UIViewController {
    @IBAction func AbstractionBtn(sender: AnyObject) {
        performSegueWithIdentifier("ShowDefinition", sender: "Abstraction")
    }

    @IBAction func binarySystemBtn(sender: AnyObject) {
        performSegueWithIdentifier("ShowDefinition", sender: "Binary System")
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "ShowDefinition") {
            if let destinationViewController = segue.destinationViewController as? EnglishViewController {
                if let definition = sender as? String {
                    if definition == "Abstraction" {
                        destinationViewController.titleMsg = "Abstraction"
                        destinationViewController.definitionMsg = "Abstraction Definition"
                    } else if definition == "Binary System" {
                        destinationViewController.titleMsg = "Binary System"
                        destinationViewController.definitionMsg = "Binary System Definition"
                    }
                }
            }
        }
    }
}