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.