Coder
Coder

Reputation: 529

fatal error when prepared to segue to view controller

I'm currently getting a fatal error unexpectedly found nil while unwrapping an optional value at destViewController.titleLabel.text = "Testing Segue".

How do I fixed it since it getting me a error when it segue to SecondViewController? How do I avoid getting nil at titleLabel.text?

class ViewController: UIViewController {

        @IBAction func action(sender: AnyObject) {

            let alertController: UIAlertController = UIAlertController (title: "Next Page", message: "", preferredStyle: .Alert)

            let yesAction = UIAlertAction (title: "YES", style: .Default ) { action -> Void in self.performSegueWithIdentifier("test", sender: self)
            }

            alertController.addAction (yesAction)

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

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

            if (segue.identifier == "test") {

               let destViewController : SecondViewController = segue.destinationViewController as SecondViewController

                destViewController.titleLabel.text = "Testing Segue"

            }
        }
    }

Upvotes: 2

Views: 174

Answers (1)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

First Of all Update your code in your ViewController like this:

class ViewController: UIViewController {

@IBAction func action(sender: AnyObject) {

    let alertController: UIAlertController = UIAlertController (title: "Next Page", message: "", preferredStyle: .Alert)

    let yesAction = UIAlertAction (title: "YES", style: .Default ) { action -> Void in self.performSegueWithIdentifier("test", sender: self)
    }

    alertController.addAction (yesAction)

    self.presentViewController(alertController, animated: true, completion: nil)
}

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

    if (segue.identifier == "test") {

        let destViewController : SecondViewController = segue.destinationViewController as SecondViewController

        destViewController.textlbl = "Testing Segue"

        }

    }
}

After that I think you can not assingn value to textLabel with your way so assign value to that label this way in your SecondViewController:

import UIKit

class SecondViewController: UIViewController {

@IBOutlet weak var titleLabel: UILabel!
var textlbl = String()
override func viewDidLoad() {
    super.viewDidLoad()

    self.titleLabel.text = textlbl
    }
}

And HERE I cerated a sample project for you for more reference.

Upvotes: 2

Related Questions