Search code examples
swiftxcodeuiviewcontrollerseguetransfer

Can't pass data between view controllers using segues (Xcode 7) (Swift)


I have been struggling to pass data between view controllers using segues. I have watched many youtube video tutorials and searched around on forums but I can't figure out why it won't work. I don't get any error messages but when I click the 'Button' the simulator crashes. I would love some help! Thanks!

Here is the code :

ViewController1 :

    import UIKit

class ViewController: UIViewController {

    @IBOutlet var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        let destViewController : ViewController2 = segue.destinationViewController as! ViewController2

        destViewController.labelText = textField.text!

    }

}

ViewController2 :

import Foundation
import UIKit

class ViewController2 : UIViewController {

    @IBOutlet var Label: UILabel!

    var labelText : String = ""

    override func viewDidLoad() {

        Label.text = labelText

    }

}

StoryBoard Image :

storyboard image


Solution

  • As stated on the comment the problem was that you were using a push segue on a UIViewController.

    Please note that push and modal segues are deprecated... Please take a look at this post entry and let me know if you have any doubts

    What's the difference between all the Selection Segues?