0

When using the prepare (forSegue) method to pass data to the destination view controller of a segue, all members of the destination VC are nil. Thus, my program crashes when trying to access these members.

My code in the source view controller:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "Second2DetailEdit"{
        var detailVC = segue.destination as! DrinkDetailViewController
        detailVC.headerLabel.text = "Edit Drink"

    }
    //...
}

The VC itself is not nil. Only all members of the VC. Did I forget something? This does only occur in my new Swift 3 project. Similar code in my Swift 2 projects have no problems. Thanks in advance.

Akar
  • 203
  • 2
  • 7

3 Answers3

2

The destination view controller's view is not created yet and that's why all IBOutlets are nil. Try sending the information you need in normal properties like Strings and in ViewDidLoad of the destination, update your view.

Hossam Ghareeb
  • 7,063
  • 3
  • 53
  • 64
2

The best way around this is to create a variable in your second view controller and set the text to that instead.

Then once the vc has initialized you can set the headerLabel.text to the new variable in viewDidLoad

Alec.
  • 5,371
  • 5
  • 34
  • 69
0

I would suggest safely unwrapping your detailVC rather than force unwrapping...

if segue.identifier == "Second2DetailEdit" {
    if let detailVC = segue.destination as? DrinkDetailViewController {
        detailVC.headerLabel.text = "Edit Drink" 
    }
}

You'll have an easier time setting properties on the destinationVC and passing info to those rather than trying to do it through UILabels...

FelixSFD
  • 6,052
  • 10
  • 43
  • 117
cmyers78
  • 76
  • 8