fatal error when prepared to segue to view controller

青春壹個敷衍的年華 提交于 2019-12-22 18:47:09

问题


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"

            }
        }
    }

回答1:


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.



来源:https://stackoverflow.com/questions/28640685/fatal-error-when-prepared-to-segue-to-view-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!