(Swift) PrepareForSegue: fatal error: unexpectedly found zero when deploying an optional value

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: nil unexpectedly found while deploying optional value

I read several pages about Options, but I did not know the answer to my problem.

Do you need more information about my project?

+6
source share
5 answers

You cannot write directly to UILabel in prepareForSegue , because the view controller is not yet fully initialized. You need to create another row property in order to save the value and place it in the label in the corresponding function - for example, viewWillAppear .

+23
source

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" } 
+11
source

This issue has recently occurred. The problem was that I was dragging segue from a specific object from my current view controller to the destination view controller - don't do this if you want to pass values.

Instead, drag it from the yellow box at the top of the window to the destination view controller. Then name segue accordingly.

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

+3
source

I had the same problem, I solved it by specifying a string that is not connected to a power outlet in the new view controller, and not referring to it in the prepareForSegue () method, in the new VC I made a label output to accept the value of an unbound string in viewDidLoad () method.

Greetings

+1
source

While the correct solution is to save the text and attach it to the label later in viewDidLoad or something else, to test the sentences, you can work around the problem by forcing the destinationViewController to build itself from the 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

0
source

Source: https://habr.com/ru/post/974150/


All Articles