Search code examples
iosswiftuiviewcontrollersegueuistoryboardsegue

How to pass data to another ViewController without using a button in swift


I currently have this Swift code which does not pass the int value that is stored in score into currentScore and higherScore into highScore. Both currentScore and highScore are both instantiated on GameOverViewController.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "GameOverVC" {
        let svc: GameOverViewController = segue.destinationViewController as! GameOverViewController
        score = svc.currentScore
        higherScore = svc.highScore
    }
}

I am currently using the storyboard to push to the next view. Here is the push code.

if let resultController = self.storyboard?.instantiateViewControllerWithIdentifier("GameOverVC") as? GameOverViewController {
    self.presentViewController(resultController, animated: true, completion: nil)
}

All the code compiles fine, so do I need to have a actual UIButton or is there something else I need to add into the method or into GameOverViewCotroller?


Solution

  • You have assign value is wrong way...

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "GameOverVC" {
            let svc: GameOverViewController = segue.destinationViewController as! GameOverViewController
            svc.currentScore = score //pass self.score to svc.currentScore
            svc.highScore = higherScore //pass self.higherScore to svc.currentScore
        }
    }