Ash Ash - 3 months ago 20
iOS Question

(Swift) Transferring Data between View Controllers

I am attempting to transfer a value between my view controllers. When I simply connect my button to the other view contoller, like soenter image description here

I am able to make it work. I am overriding prepareforSegue.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var DestinationViewController : ViewTwo = segue.destinationViewController as! ViewTwo
DestinationViewController.scoretext = score.text!
}


It all works fine but when I open the other controller programatically, the value isn't transferred. This is the code I'm using for that...

let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc : ViewTwo = storyboard.instantiateViewControllerWithIdentifier("viewtwo") as! ViewTwo

self.presentViewController(vc, animated: true, completion: nil)

Answer

When you use instantiateViewControllerWithIdentifier, prepareForSegue is not called. You will have to assign scoretext after instantiation only.

        let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let vc : ViewTwo = storyboard.instantiateViewControllerWithIdentifier("viewtwo") as! ViewTwo
        vc.scoretext = score.text!
        self.presentViewController(vc, animated: true, completion: nil)