(Swift) PrepareForSegue: fatal error: unexpectedly

2019-01-24 09:33发布

DetailViewController:

    @IBOutlet var selectedBundesland: UILabel!

TableViewController:

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


    if (segue.identifier == "BackToCalculator") {
        var vc:FirstViewController = segue.destinationViewController as FirstViewController
            vc.selectedBundesland.text = "Test"
    }

IBOutlet is connected!

Error: fatal error: unexpectedly found nil while unwrapping an Optional value

I read multiple pages about Optionals but i didn't know the answer to my problem.

Do you need more information about my project?

5条回答
在下西门庆
2楼-- · 2019-01-24 09:52

I just had the same problem, I solved it by defining a string that is not connected to an outlet in the new view controller and than referring to it in the prepareForSegue() method, in the new VC I made the label outlet to take the value of the non connected string in the viewDidLoad() method.

Cheers

查看更多
Rolldiameter
3楼-- · 2019-01-24 09:57

Recently had this problem. The problem was that I had dragged the segue from a specific object from my current view controller to the destination view controller - do not do this if you want to pass values.

Instead drag it from the yellow block at the top of the window to the destination view controller. Then name the segue appropriately.

Then use the if (segue.identifier == "BackToCalculator") to assign the value as you are currently. All should work out!

查看更多
仙女界的扛把子
4楼-- · 2019-01-24 10:05

DetailViewController:

var textValue: String = ""
@IBOutlet weak var selectedBundesland: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    selectedBundesland.text = textValue
}

TableViewController:

     if (segue.identifier == "BackToCalculator") {  
         var vc:FirstViewController = segue.destinationViewController as FirstViewController
         vc.textValue = "Test"
}
查看更多
\"骚年 ilove
5楼-- · 2019-01-24 10:08

You cannot write directly to the UILabel in prepareForSegue because the view controller is not fully initialised yet. You need to create another string property to hold the value and put it into the label in the appropriate function - such as viewWillAppear.

查看更多
ら.Afraid
6楼-- · 2019-01-24 10:09

While the correct solution is to store the text and attach it to the label later in viewDidLoad or something, for testing proposes, you can bypass the issue by forcing the destinationViewController to build itself from storyboard by calling its view property like:

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

     if (segue.identifier == "TestViewController") {
          var vc:FirstViewController = segue.destination as! TestViewController
          print(vc.view)
          vc.testLabel.text = "Hello World!"
     }
}

made for Swift 3.0 with love

查看更多
登录 后发表回答