m1234 m1234 - 1 year ago 60
Swift Question

Finding nil when prepareForSegue Swift

I am not at all sure why this is happening. When I try to use prefpareForSegue I get "Unexpectedly found nil while unwrapping optional values". I know what it means and where it is happening but I have no clue why.

There error happens on either of the lines marked in my code. I have already tested the values

dateText
and
currentDate
and neither are nil.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

var DestViewController : CreatePostScrollViewController = segue.destinationViewController as! CreatePostScrollViewController

if dateText != "" {

DestViewController.startTimeDateButton.setTitle(dateText, forState: .Normal)// Error Here

} else if dateText == "" {

DestViewController.startTimeDateButton.setTitle(currentDate, forState: .Normal)// Error Here
}
}


Any help is much appreciated!

Answer Source

When prepareForSegue is called, the user interface elements of the destination controller might not yet be initialized. What you should instead do, is have a field in CreatePostScrollViewController like this:

var buttonTitle: String?;

Then in your viewWillAppearMethod within CreatePostScrollViewController set the button's title to the buttonTitle field you have like this:

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated);
    if let buttonTitle = buttonTitle {
        startTimeDateButton.setTitle(buttonTitle, forState: .Normal);
    }
}

Finally to finish the tale in the prepareForSegue do:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    var DestViewController : CreatePostScrollViewController = segue.destinationViewController as! CreatePostScrollViewController

    if dateText != "" {

        DestViewController.buttonTitle = dateText

    } else if dateText == "" {

        DestViewController.buttonTitle = currentDate
    }
}