Search code examples
swiftviewcontrollernavigationcontroller

PushViewController shows Black Screen


i have a problem with my App.

I´m not an experienced programmer, so maybe it´s just a simple solution. I thought this problem exists because i´m just trying things and play with my app so i made a new App and there´s the same problem.

When i push to a ViewController with navigationController?.pushViewController(PinkViewController(), animated: true).

I´m getting just a black screen. If i have a code like Label.text = "String in viewdidload of the PinkViewController(). I get the following error at this line of code:

fatal error: Unexpectedly found nil while implicitly unwrapping an Optional

I searched the web and i didn´t find any solutions for this problem. I hope you can help me.


Solution

  • The reason why it crashes is that your label is probably defined as an @IBOutlet that is connected to a UILabel in your storyboard's PinkViewController. However, when you instantiate PinkViewController with an empty constructor, you're not "using the storyboard-way" and your label outlet (which is non-optional, because it's likely to have an exclamation mark there) could not have been connected to the storyboard instance of your view controller.

    So what you should do is one of these options:

    If you defined PinkViewController in the storyboard, you'd have to instantiate it in a nib kind of way, for example:

    In your Storyboard, select the view controller and then on the right side in the Identity Inspector, provide a Storyboard ID. In code you can then call this to instantiate your view controller and then push it:

    let pinkViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "yourIdentifier")
    

    Even better, you create a Segue in the storyboard by control-dragging from the current VC to PinkViewController. There's lots of tutorials for creating Segues online. Don't forget to provide an Identifier for the Segue in the Storyboard, if you want to trigger it programmatically. This can be done by calling

    self.performSegue(withIdentifier: "yourIdentifier", sender: nil)
    

    If you want to trigger that navigation upon a button click, you can even drag the Segue from the button to PinkViewController, that way you wouldn't even need to call it in code.

    If you defined PinkViewController programmatically only (by creating a class named like that which conforms to UIViewController), you might wanna instantiate it with PinkViewController(nibName: nil, bundle: nil) (notice the arguments instead of an empty constructor) and then push it with your provided code.

    Hope that helps, if not, please provide further code / project insight.